This builds on concepts discussed in this question How to manage Castle Windsor dependencies in a nuget library.
I am working on a project which uses Castle.Windsor for DI and references several custom NuGet packages. I have installed Castle.Windsor in one of the class libraries (let's call it MyNugetLib) referenced via NuGet and I've defined an extension method on IWindsorContainer in this library which registers the local services.
public static class WindsorContainerExtensions
{
public static void RegisterMyNugetLibServices(this IWindsorContainer container)
{
container.RegisterLocalServices();
}
private static void RegisterLocalServices(this IWindsorContainer container)
{
container.Register(...)
}
}
The project that references this NuGet package (let's call it MyProj) uses Windsor as well and in the installer it calls the extension method defined in the NuGet package. This all works. My question is how do I pass the Windsor container reference to MyNugetLib from MyProj? I have tried injecting IWindsorContainer in the constructor of a class where I need it, but this class uses Lazy instantiation as follows:
private static readonly Lazy<MyClass> LazyInstance = new Lazy<MyClass>(() => new MyClass());
private MyClass() {}
public static MyClass Instance => LazyInstance.Value;
From MyProj this is called as follows:
Lib.MyClass.Instance
The only way in which I've managed to make this work is exposing a public property in MyClass which is used in MyProj to set the WindsorContainer
public IWindsorContainer DIContainer { get; set; }
in MyProj
Lib.MyClass.DIContainer = MyProj.WindsorContainer
I don't particularly like this. Is there a better way of doing this?
Update: (thanks to insane_developer's suggestions)
The question really is: how do you inject dependencies in a Lazy constructor? If I could do this, then I could remove the dependency on Windsor from MyNugetLib.
So I would have
private IService1 service1;
private IService2 service2;
private MyClass(IService1 myService1, IService2 myService2)
{
this.service1 = myService1;
this.service2 = myService2
}
public static MyClass Instance => LazyInstance.Value;
private static readonly Lazy<MyClass> LazyInstance = new Lazy<MyClass>(() => new MyClass(???));
How do I write the func above so it injects dependencies in my constructor?
Lib.MyClass.DIContainer
, can you explain it again? – Matteo Umili