Register the same type to multiple interfaces

浪尽此生 提交于 2019-12-18 12:25:47

问题


It is possible to register one type to multiple interfaces?

I have class that implement two interfaces

MyService : IService1, IServier2 {}

I would like to register this type for both interfaces.

container.RegisterType<IService1, MyService>(CreateLifetime());
container.RegisterType<IService2, MyService>(CreateLifetime());

Unfortunately during after resolving I have two different instances. I tried use common lifetime but then I got message that I can't.


回答1:


I usually write this:

      .RegisterType<MyService>(CreateLifeTime())
      .RegisterType<IService1, MyService>()
      .RegisterType<IService2, MyService>();

Of course with a TransientLifetimeManager, you still will get two different instances of MyService.

The code above works with PerResolveLifetimeManager, PerResolveLifetimeManager, PerThreadLifetimeManager.




回答2:


You can do this by config as well:

<register type="MyService" name="MyServiceName">
    <lifetime type="singleton" />
</register>
<register type="IService1" mapTo="MyService" />
<register type="IService2" mapTo="MyService" />



回答3:


I based my answer on @StephenTunney's answer, but I couldn't get his to work.

You can do this by config as well:

<register type="MyService" name="MyServiceName">
    <lifetime type="singleton" />
</register>
<register type="IService1" mapTo="MyService">
    <lifetime type="singleton" />
</register>
<register type="IService2" mapTo="MyService">
    <lifetime type="singleton" />
</register>

Note that the name="MyServiceName" is optional and only required if you plan on doing named instances.



来源:https://stackoverflow.com/questions/11115298/register-the-same-type-to-multiple-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!