Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating an Object as a service in ASP.net Core

Very inexperienced with Asp.Net, and I have a class that I want to be able to instantiate and use across some controllers, and I'm not really sure how to get arguments to my constructor.

I have a data type that I would like to use as a service called Watcher which has a constructor signature of Watcher(string _path, bool _DeletionPolicy = false) this provides a path to watch files, and sets the default deletion policy. (False is do nothing after expiration, a file "expires" after 90 days.)

I understand that I need to register the service with MVC in ConfigureServices(), but how would I go about instantiating those two (or one required) parameter?

like image 912
Chris Rutherford Avatar asked Dec 23 '22 04:12

Chris Rutherford


2 Answers

in brief you will have to do something like this:

Write your Watcher class that implements IWatcher interface:

public class Watcher : IWatcher
{
    private readonly string _path;
    private readonly bool _deletionPolicy;

    public Watcher(string path, bool deletionPolicy = false)
    {
        _path = path;
        _deletionPolicy = deletionPolicy;
    }
}

then in ConfigureServices method in Startup.cs register IWatcher to the Watcher class like this:

services.AddTransient<IWatcher>(w => new Watcher("some path", deletionPolicy));

Finall, in every controller where you need the Watcher class, use the IWatcher interface in a constructor. When you add the IWatcher to a controller constructor, the dependency injection will instantiate the Watcher as you have defined it in a ConfigureServices method. After that it will inject it in constructor and will assign it to a private variable. Then you can use it within controller in a methods where needed.

public class SomeController : Controller
{
    private readonly IWatcher _watcher;

    public SomeController(IWatcher watcher)
    {
        _watcher = watcher;
    }   
}   
like image 149
juramarin Avatar answered Jan 06 '23 12:01

juramarin


Use the factory delegate when adding the service

For example

services.AddTransient<Watcher>(sp => new Watcher("some path here", otherVariable));

From there when using the service as a dependency,

either via constructor injection

private readonly Watcher watcher;

//ctor
public MyController(Watcher watcher) {
    this.watcher = watcher;
    //...
}

or directly in an action

public IActionResult MyAction(int arg, [FromServices]Watcher watcher) {

}

the container will use that delegate when activating the class for injection.

like image 38
Nkosi Avatar answered Jan 06 '23 12:01

Nkosi