Register the same type to multiple interfaces

后端 未结 3 1665
天命终不由人
天命终不由人 2020-12-30 08:00

It is possible to register one type to multiple interfaces?

I have class that implement two interfaces

MyService : IService1, IServier2 {}

相关标签:
3条回答
  • 2020-12-30 08:36

    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.

    0 讨论(0)
  • 2020-12-30 08:40

    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" />
    
    0 讨论(0)
  • 2020-12-30 08:44

    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.

    0 讨论(0)
提交回复
热议问题