Search code examples
c#asp.net-web-apidependency-injectioninversion-of-control

Instantiate class with automatically using dependency types added in Startup.cs


Example code:

public class A
{
public DoWork()
{
   //how to Instantiate an object of class B with automatically using dependency service types added in Startup.cs and IServiceCollection?
   var b = some resolver logic here to get new B();//need help here
   b.InnerWork();
}
}

public class B
   //What can help pass the configured dependency types and give a new instance of B?
   public B(Dep1 one, Dep2 two) {}
   function bool InnerWork() {}

Can't seem to find syntax to access the IServiceCollection or a resolver that would help make an instance of class B.


Solution

  • If I understood your question properly:

    public class A
    {
        private readonly IServiceProvider _provider;
        public A(IServiceProvider provider) =>
            _provider = provider;
        
        public void DoWork()
        {
            var scope = _provider.CreateScope();
            var b = scope.ServiceProvider.GetRequiredService<B>();
            b.InnerWork();
        }
    

    Or you can inject B into A instead of using IServiceProvider like the previous author said.