Unity:将容器配置为以多种方式解析为相同类型

时间:2016-08-05 09:53:58

标签: c# interface unity-container

考虑这些接口和类

interface IWorkflowService
{
    void FillContext(WFContext context, IWorkflowableEntity entity);
}

interface IDataService<Entity> 
{
}

abstract class DataService<TEntity>
{      
}

class EmployeeDataService : IWorkflowService, DataService<Employee>
{
}

class WorkflowHandler
{
    private IUnityContainer _container;

    public bool Handle(IWorklfowableEntity entity)
    {
        // now I want to resolve the correct IWorkflowService
        // suppose entity is an employee Entity
        // EmployeeDataService should be resolved
    }
}

//container definition:
container.RegisterType<IDataService<employee>, EmployeeDataService>();

在Workflhandler中,我想解决正确的IWorkflowService,它依赖于给定实体的类型。

  1. 如何基于IWorkflowService和我的实体的Employee类型定义我的Unity容器以获取EmployeeDataService?
  2. 我应该如何从Workflowhandler中的Handle方法调用它?
  3. 顺便说一句:也许我误用Unity作为服务定位器。如果是这种情况,我应该创建自己的服务定位器来获得正确的服务吗?

    提前感谢任何想法和答案。

1 个答案:

答案 0 :(得分:0)

正如我怀疑的那样,将统一容器用作服务定位器被认为是一种弊端。

相反,workflowhandler类应该依赖于工厂。当您编写横切特征并使用依赖注入时,通常需要这样做。

因此,WorkflowHandler看起来像这样:

class WorkflowHandler 
{
    private IWorkflowServiceFactory _wfsfactory

    public WorkflowHandler(IWorkflowServiceFactory workflowservicefactory)
    {
        _wfsfactory = workflowservicefactory;
    }

    public bool Handle(IWorklfowableEntity entity)
    {
        var svc = _wfsfactory.GetServiceByEntity(entity);
        var context = new WfContext();
        svc.FillContext(context, entity);

        //handle evaluate etc.
    }
}

服务工厂看起来像这样:

class WorkflowServiceFactory : IWorkflowServiceFactory
{
    private IUnityContainer _container;

    public GetServiceByEntity(IWorkflowableEntity entity)
    {
        Type t = typeof(IDataService<>);
        Type fulltype = t.MakeGenericType(new [] { entity.GetType() });

        return _container.Resolve(fulltype);
    }

}