Service Transfer Using Dependency Injection and Factory Pattern in ASP.NET

I am using ASP.NET Core, I know that such a logging mechanism is already provided by the framework, but using this to illustrate my problem.

I use the Factory template to create the Logger class, since I do not know the type of logging (because it is stored in the database).

ILogger Agreement

Log(string msg)

LoggerFactory will then return an ILogger after creating the Logger based on the parameter passed from the DB:

public class LoggerFactory
{
    public static Contracts.ILogger BuildLogger(LogType type)
    {
        return GetLogger(type);
    }

//other code is omitted, GetLogger will return an implementation of the related logger

Now that I need to use Logger, I have to do it like this:

  public class MyService
{
    private ILogger _logger
    public MyService()
    {
        _logger = LoggerFactory.BuildLogger("myType");
    }

But I intend to save my classes without any instances, I need to use Constructor DI in MyService, and I need to enter all the Startup dependencies:

    services.AddTransient<Contracts.ILogger, LoggerFactory.BuildLogger("param") > ();

, . DI, ?

+2
1

:

  • LoggerFactory, .
  • , .
  • , ILogger - , . , .
  • factory , Root of Composition, .

    , , DI ASP.NET Core , ILogger, .

    Core Core ASP.NET . :

    services.AddTransient<MyService>(c => new MyService(
        BuildLogger(typeof(MyService).Name),
        c.GetRequiredService<ISomeOtherDependency>(),
        c.GetRequiredService<IYetAnotherOne>());
    
+4

Source: https://habr.com/ru/post/1666609/


All Articles