Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register the same type to multiple interfaces

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.

like image 784
Sławomir Rosiek Avatar asked Jun 20 '12 08:06

Sławomir Rosiek


1 Answers

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.

like image 179
onof Avatar answered Sep 28 '22 06:09

onof