Home > OS >  Dependency Injection in library in .NET
Dependency Injection in library in .NET

Time:08-21

Lets say I have a CustomClass class from a library that does somethings with a IWebHostEnvironment service. And I wish to create and use this library inside a PageModel like shown below:

public class CustomClass
{
    private readonly IWebHostEnvironment _environment;

    public CustomClass(IWebHostEnvironment environment){
        _environment = environment
    }
    public printEnvironment(){
        Console.WriteLine(_environment.ContentRootPath);
    }
}
public class Index : PageModel
{
    private readonly IWebHostEnvironment _environment;

    public Index(IWebHostEnvironment environment)
    {
        _environment = environment;
    }

    public void OnGet()
    {
        var cc = new CustomClass(environment);
        cc.printEnvironment()
    }
}

Is there a way to write this CustomClass where it will automatically have access to the IWebHostEnvironment without me having to inject it from the PageModel?

I know this doesn't make much sense. The reason I'm asking this is because I'm upgrading a WebApp from .NET Framework, where dependency injections weren't a thing, to .NET Core.

CodePudding user response:

Somewhere you must register this class of yours

// if you go without interface directly DI can instantiate your type
services.AddTransient(typeof(CustomClass));

// With interface will look like
services.AddTransient<ISomeInterface, CustomClass>();
// for this ^^ your class must be declared as 
public class CustomClass : ISomeInterface .......


// THEN

public class CustomClass
{
    private readonly IWebHostEnvironment _environment;

    public CustomClass(IWebHostEnvironment environment){
        _environment = environment
    }
    public printEnvironment(){
        Console.WriteLine(_environment.ContentRootPath);
    }
}

public class Index : PageModel
{

    private readonly CustomClass _customClass; 

    public Index(CustomClass customClass)
    {
        _customClass = customClass;
    }

    public void OnGet()
    {
        //var cc = new CustomClass(environment); // no more needed
        _customClass.printEnvironment()
    }
}

// with interface will look like this
public class Index : PageModel
{
    private readonly ISomeInterface _customClass; 

    public Index(ISomeInterface customClass)
    {
        _customClass = customClass;
    }

    public void OnGet()
    {
        
        _customClass.printEnvironment()
    }
}

Bottom line here is - if your dependency injection knows how to get IWebHostEnvironment, merely registering your class like

services.AddTransient(typeof(CustomClass));

or

services.AddTransient<ISomeInterface, CustomClass>();

will be enough to DI inject implementation of IWebHostEnvironment into your custom class

  • Related