是否使用隐式/显式转换者违反赞成干单一责任模式? [英] Does using Implicit / Explicit conversion operators violate Single Responsibility Pattern in favor of DRY?

查看:174
本文介绍了是否使用隐式/显式转换者违反赞成干单一责任模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要这两个类之间进行转换,并希望保持干,但不违反单一职责模式...

I need to convert between these two classes, and want to maintain DRY but not violate the Single Responsibility Pattern...

public class Person
{
    public string Name {get;set;}
    public int ID {get;set;}
}

public class PersonEntity : TableServiceEntity
{
    public string Name {get;set;}
    public int ID {get;set;}

    // Code to set PartitionKey
    // Code to set RowKey
}

更多资讯

我在我的ASP.NET MVC应用程序的一些模型对象。由于我与Azure存储工作,我看到了需要转换和从视图模型对象和AzureTableEntity经常。

I have some Model objects in my ASP.NET MVC application. Since I'm working with Azure storage I see the need to convert to and from the ViewModel object and the AzureTableEntity quite often.

我已经正常完成的这个变量左手右手分配在我的控制器。

I've normally done this left-hand-right-hand assignment of variables in my controller.

Q1

除了隐/显式转换,应此code是在控制器(X)或在DataContext (Y)

Aside from implicit/explicit conversion, should this code be in the controller(x) or the datacontext(y)?

Person <--> View <--> Controller.ConverPersonHere(x?) <--> StorageContext.ConvertPersonHere(y?) <--> AzurePersonTableEntity

Q2

我应该做一个隐性或显性的转换?

Should I do an implicit or explicit conversion?

Q3

什么对象应包含转换code?

What object should contain the conversion code?

更新

我也是在这个项目实施WCF和我不知道这将如何影响你的建议。另请参阅<一个href=\"http://stackoverflow.com/questions/5092736/if-wcf-is-in-a-mvc-application-should-it-use-the-controller-to-access-the-databa\">this问题。

I'm also implementing WCF in this project and am not sure how this will affect your recommendation . Please also see this question.

推荐答案

Q1:控制器

Q2:手动或使用映射工具的帮助,如AutoMapper转换

Q2: Convert manually or with the help of a mapping tool such as AutoMapper.

Q3:我会把code代表这一个转换器或映射器类如下所示。需要注意的是IConverter是所有转换器之间共享,而只是IPersonConverter存在让你的控制器和服务定位器可以使用它。

Q3: I would put the code for this in a converter or mapper class like the following. Note that IConverter is shared among all converters, and IPersonConverter just exists so your controllers and service locators can use it.

public interface IConverter<TModel, TViewModel>
{
    TViewModel MapToView(TModel source);
}

public interface IPersonConverter : IConverter<PersonEntity, Person>
{
}

public class PersonConverter : IPersonConverter
{
    #region IPersonConverter

    public Person MapToView(PersonEntity source)
    {
        return new Person
                   {
                       ID = source.ID,
                       Name = source.Name
                   };

        //or use an AutoMapper implementation
    }

    #endregion
}

这篇关于是否使用隐式/显式转换者违反赞成干单一责任模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆