2015-05-01 33 views
0

目前我有两个不同的版本已在途中的API作品的一些重大分歧的内部业务对象的工作。在发布针对两个版本业务对象的产品时,我有两个单独的项目和安装程序。这导致了很多重复的代码。了两个不同版本的企业C#包装对象

是否可以写一个包装它会暴露一个一致的API可能再由一个单一的项目,可以用两种不同的配置来确定要使用的业务对象可以用吗?

NB目前业务对象是作为一个dll提供的,我无法访问源代码。

+1

如果业务对象和业务逻辑之间有很强的相似性,你可以使用通用接口或对象继承来减少重新编码相同的片段。 – ryanyuyu

+0

适配器模式可能也很有用,如果您想包装较旧的适配器模式以使其“行为”像新的一样。 –

+0

您可以使用封装类来解决此问题,该封装类反过来使用反射来调用这两个对象。但是,如果您有许多业务对象需要用这种方式解决,那么这可能会成为维护噩梦。这不是一个好的解决方案,但它至少是一种选择。 –

回答

1

正如@jacobRoberts说,可以使用DI容器与IOC具体地,一个允许登记经由xml配置例如团结,温莎城堡等

它是如何工作的? 您将使用抽象,但不是实现。意味着而不是使用Business Object类,您必须使用Interface。 例如

public interface IBusinessObj 
{ 
void DoBusiness(); 
} 

public class BusinessObj1 : IBusinessObj 
{ 
    public void DoBusiness() 
    { 
    // Your implementation based goes here specific to BusinessObj1 type 
    } 
} 

public class BusinessObj2 : IBusinessObj 
{ 
    public void DoBusiness() 
    { 
    // Your implementation based goes here specific to BusinessObj2 type 
    } 
} 

现在让我们去消费阶层:

public class UILayerController 
{ 
// Here either you can use the Property injection 
public IBusinessObj MyBusinessStuff {get; set ;} 

// OR 
//you can use the constructor injection with private field 
private IBusinessObj _myBusinessStuff 
public UILayerController(IBusinessObj myBusinessStuff) 
{ 
    _myBusinessStuff = myBusinessStuff; 
} 
} 

现在你需要创建一个注册类或DIContainer这将帮助你在运行时解决您的实例。

this article for using Unity for registration via Configuration or via class.

更新: 如果你想使用类的名称,而不是接口,你可以做到这一点与统一。只需替换Interface by Business实体类名称并在Unity类中保留注入类型。现在,在设计的时候配置您可以添加类似:

<configuration> 
    <configSections> 
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" /> 
    </configSections> 
    <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 
    <container> 

     <register type="YourApplication.BusinessObjectClass" mapTo="<ProvidedDll1>.<Namespace>.BusinessObjectClass" /> 

     <!-- For second business class just change the mapping to --> 

     <register type="YourApplication.BusinessObjectClass" mapTo="<ProvidedDll2>.<Namespace>.BusinessObjectClass" /> 

    </container> 
    </unity> 
</configuration> 

这里mapTo属性将具有类的驻留在企业的dll的完整的命名空间。现在

团结容器的intialization会是这样的:你需要

UnityContainer container = new UnityContainer(); 
container.LoadConfiguration(); 

因此,下一次添加不同的实现。你只需要为此添加一个单独的统一配置文件。 看到这个thread how to split the configuration in separate files for Configurations.

+0

感谢您的详细回复。我已经修改了上面的问题,因为业务对象是作为两个DLL提供的,我不确定上述解释是否适用于此场景。 – seanzi

+0

我需要更多的细节来回答这种情况,这些dll是否具有相同的商业实体类名?你可以改变Consumer类的实现吗? – vendettamit

+0

dll具有相同的名称,命名空间和类名也相同。一个只是具有额外功能的更新版本。目前我正在调查,看看这是否可行,任何将使用包含单个API的新dll的代码都可以更改。 – seanzi

0

你可以写你的业务类实现,然后,你想成为一个工厂模式应该让你的接口。