castleproject/Windsor

Dependency injection extension register services in container and use as default

MestreDosMagros opened this issue · 2 comments

Hello, I'm working on legacy code that uses both Windsor container as well as native ServiceCollection on WebApi project, the problem is that there are projects that use Windsor as DI resolver, and others that use the native ServiceCollection from .net core.

I found that i could reuse the registrations made on windsor container and set this as default for the WebApi project using UseWindsorContainerServiceProvider().

But the problem is: I can register services on the native ServiceCollection and those services can be used with no problem, but not if I take the other way around.

Take this as example:

When using Castle.Windsor.Extensions.DependencyInjection, if I do: services.AddTransient<MyService>() i can resolve the service with no problem and i can make sure that Windsor is the default resolver, but when i use this: container.Register(Component.For<MyService>().ImplementedBy<MyService>().LifestyleTransient()); I can´t resolve this. Just when I register in the ServiceCollection as well, I don´t want to register all services again in the native ServiceCollection, as this will not make sense for the project and with the work for doing this is the same as if I would remove Windsor completly from the project and keep using just the native ServiceCollection.

There are any way i can use Castle.Windsor.Extensions.DependencyInjection for registering all my services in Windsor and then use as the default DI resolver?

If you create the WindsorServiceProviderFactory before registering components this works just fine:

var svc = new ServiceCollection();
var container = new WindsorContainer();
var f = new WindsorServiceProviderFactory(container);

svc.AddTransient<A>();
container.Register(Component.For<B>().ImplementedBy<B>().LifestyleTransient());

var sp = f.CreateServiceProvider(f.CreateBuilder(svc));

Console.WriteLine(sp.GetService<A>());
Console.WriteLine(sp.GetService<B>());

I figured this out couple hours after this question, I have used this in all my apps that uses Windsor and it is not a web project and it works as expected