DI和JSON.NETDI、JSON、NET

2023-09-03 16:34:41 作者:旧城冷巷雨未停

我用JSON.NET序列化和反序列化对象为不同的目的。我是DI的忠实粉丝,但低于code给我发冷。是闻起来像坏code:

I'm using JSON.NET to serialize and deserialize object for different purposes. I'm a big fan of DI but the code below gives me the chills. Is smells like bad code:

public class Foo : Baz
{
    private readonly IBar bar;

    public Foo()
        : this(ObjectFactory.GetInstance<IBar>())
    { }

    public Foo(IBar bar)
    {
       if (bar == null)
            throw new ArgumentNullException("bar");

       this.bar = bar;
    }

   ... rest of class ...
}

默认构造函数是给我发冷的东西。我把这个添加到支持造成JSON.NET反序列化:

The default constructor is the thing that gives me the chills. I've added this to support the deserialization caused by JSON.NET:

string jsonString = ...;
string concreteBazType = ...;

Baz baz = (Baz)JsonConvert.DeserializeObject(jsonString, Type.GetType(concreteBazType);

从抽象基类巴兹注意,类Foo inherrits!

Notice the class Foo inherrits from the abstract base class Baz!

我的问题给你DI和JSON.NET爱好者在那里:我怎样才能改变code,以避免code-闻到默认的构造函数给我上课富?

My question to all you DI and JSON.NET geeks out there: how can I change to code to avoid the code-smell the default constructor gives me in class Foo?

推荐答案

这是一个常见的​​问题有各种数据传输对象< /一>,它们是否适合JSON.NET,WCF或其他技术。事实上,你可以说,所有的应用程序边界面对类受到这个问题的一个学位或其他。问题是等价的Windows窗体控件和其他显示技术。

This is a common problem with all sorts of Data Transfer Objects, whether they fit into JSON.NET, WCF or other technologies. In fact, you could say that all application boundary-facing classes suffer from this problem to one degree or the other. The problem is equivalent for Windows Forms Controls and other display technologies.

在应用程序栈的另一端,我们看到了同样的问题,配置对象,并可能与某些类型的ORM(如实体框架类)。

In the other end of the application stack, we see the same issue with Configuration objects and potentially with some ORM types (such as Entity Framework classes).

在所有的情况下,最好的办法是把所有的这种边界的对象作为哑类型比行为更加结构。我们已经知道,这是正确的事情做对WCF DataContracts,ASP.NET MVC视图,Windows窗体控件等,因此这将是一个众所周知的解决问题的方法。

In all cases, the best approach is to treat all such Boundary Objects as dumb types with more structure than behavior. We already know that this is the right thing to do for WCF DataContracts, ASP.NET MVC Views, Windows Forms Controls, etc. so it would be a well-known solution to the problem.

就像我们有控制器来填充在UI视图,我们可以有业务运营,映射器和诸如此类的东西映射DTO的域对象。换句话说,你最好的追索权将是不打算在所有序列化的Foo。

Just like we have Controllers to populate Views in a UI, we can have service operations, mappers and whatnot that map DTOs to Domain Objects. In other words, your best recourse would be to not attempt to serialize Foo at all.

相反,定义了一个 FooJson 类重presents美孚的静态结构和使用映射器在两者之​​间进行转换。

Instead, define a FooJson class that represents the static structure of Foo and use a Mapper to translate between the two.