Search code examples
c#dependency-injectioncastle-windsor.net-2.0microsoft-extensions-di

What's the Microsoft DI equivalent of Castle.Windsor's DependsOn Dependency.OnValue


I have a .NET Standard 2.0 library which has DI set up in the following way,

container.Register(Component.For<IMyFactory>()
    .ImplementedBy<MyFactory>()
    .DependsOn(Dependency.OnValue("connectionString",
        container.Resolve<IDataAccess>().ConnectionString))
    .LifestyleSingleton());

container.Register(Component.For<IMyAdapter>()
    .ImplementedBy<MyAdapter>().LifestyleTransient());

What are the equivalent of these statements in Microsoft.Extensions.DependencyInjection?

I want to move away from Castle.Windsor dependencies.


Solution

  • services.AddSingleton<IMyFactory>(sp =>
        ActivatorUtilities.CreateInstance<MyFactory>(
            sp,
            sp.GetRequiredService<IDataAccess>().ConnectionString));
    
    services.AddTransient<IMyAdapter, MyAdapter>();