【问题标题】:Unity resolve parameter with named mapping具有命名映射的统一解析参数
【发布时间】:2012-11-08 04:45:58
【问题描述】:

我正在使用统一来解析对象图。

public interface ISessionManager
{
}

public class DefaultSessionManager : ISessionManager
{
}

public class OnCallSessionManager : ISessionManager
{
}

我有在构造函数上使用 ISessionManager 的服务类

public class CustomerService
{
    public class CustomerService(ISessionManager sessionManager)
    {
    }
}

在对象图之上。我有一个视图模型类和一个数据管理器类。

public class ViewModel(CustomerService customerService)
{
}

public class DataManager(CustomerService customerService)
{
}

现在我想使用不同的 ISessionManager 解析 ViewModel 和 DataManager。 对于ViewModel 类,我想要DefaultSessionManagerOnCallSessionManager 对于DataManager。我该怎么做?

提前致谢。

【问题讨论】:

    标签: c# unity-container


    【解决方案1】:

    在代码中使用配置,您可以注册如下内容:

    var container = new UnityContainer();
    
    container.RegisterType<ISessionManager, DefaultSessionManager>()
      .RegisterType<ISessionManager, OnCallSessionManager>("oncall")
      .RegisterType<CustomerService>()
      .RegisterType<CustomerService>(
        "oncall",
        new InjectionConstructor(
          new ResolvedParameter(
            typeof(ISessionManager),
            "oncall")))
      .RegisterType<ViewModel>()
      .RegisterType<DataManager>(
        new InjectionConstructor(
          new ResolvedParameter(
            typeof(CustomerService),
            "oncall")));
    

    它丑得要命,但它应该可以解决问题。

    【讨论】:

      猜你喜欢
      • 2013-06-08
      • 2012-10-26
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多