使用Unity有条件地注入依赖

时间:2015-09-25 13:57:39

标签: c# asp.net-mvc dependency-injection

我正在使用Unity(DI)将注册服务注入我的控制器。

控制器

public class RenewalController : Controller
{
    private readonly IRegistrationService _registrationService;
    private readonly IRenewalTypedFactory _renewalFactory;

    public RenewalController(IRegistrationService registrationService, IRenewalTypedFactory renewalFactory)
    {
        _renewalFactory = renewalFactory;
        _registrationService = registrationService;
    }

    // GET: Renewal
    public ActionResult Renew()
    {
        return View();
    }

Unity配置

container.RegisterType<IRegistrationService, RegistrationService>(new PerRequestLifetimeManager());

已经有注册服务,但我现在必须创建一个覆盖方法的续订服务类。

public class RenewalService : RegistrationService, IRegistrationService
{
   ...
}

如果我的控制器要求,我如何告诉我的Unity配置注入我的IRegistrationService续订服务?

我知道在Ninject你会做类似的事情:

.WhenInjectedInTo(typeof(RenewalController));

我已经阅读了这个问题,但无法理解它,或将它应用于我的例子:

How to conditionally bind a instance depending on the injected type using unity?

1 个答案:

答案 0 :(得分:1)

告诉容器它应该注入RenewalController

的依赖关系
container.RegisterType<RenewalController>(new InjectionConstructor(
             new ResolvedParameter<RenewalService>(), 
             new ResolvedParameter<IRenewalTypedFactory>()));