Home > Net >  (.net core3.1) custom services in function dependency injection
(.net core3.1) custom services in function dependency injection

Time:11-23

Recently began to learn the.net core, oneself write while I watched video to learn something, and then saw a video about b station method of dependency injection

Basic service usage
 
Public class MyClass
{
Private readonly IMyService _service;
Public MyClass (IMyService service)
{
_service=service;
}
}

Then the video tells a custom dependency injection method
 
Public interface IEngine
{
T Resolve () where T: class;
}
Public class EnginContext
{
Private static IEngine _engine;


[MethodImpl (MethodImplOptions. Synchronized)]
Public static IEngine Initialize (IEngine engine)
{
If (_engine==null)
_engine=engine;
Return _engine;
}

Public static IEngine Current
{
The get
{
Return _engine;
}
}
}
Public class MyEngine: IEngine
{
Private IServiceProvider _serviceProvider;
Public MyEngine (IServiceProvider serviceProvider)
{
Enclosing _serviceProvider=serviceProvider;
}

Public T Resolve () where T: class
{
Return _serviceProvider. GetService (a);
}
}
//startup. Cs to add service
EnginContext. The Initialize (new MyEngine (services. BuildServiceProvider ()));
//and then you can in the constructor does not use the parameters of injection
Public BaseClass ()
{
_menu=EnginContext. Current. Resolve (a);
}

Using this method can be directly in the function dependency injection
Then I would like to ask two bosses problems
1 video tutorial because core2.0, 2.0 so I tried with no problem, but now I do things core3.1, it came with a warning: warning ASP0000 Calling 'BuildServiceProvider from application code results in an additional copy of singleton services being created. Consider alternatives to the as dependency injecting services as the parameters to' Configure '.
English can read but don't understand what he said, the other the how should change?
2 when using inheritance, that is, if a base class to use the service with the method of the constructor parameters appeared to inherit the service variable will not be assigned, there is no other way can need not parameters directly in function dependency injection

CodePudding user response:

Using autofac, you can through property injection,
There are some other ioc, you check,

CodePudding user response:

https://www.itsvse.com/thread-7563-1-1.html

CodePudding user response:

Tip to the first question should be to create a service, there is a way to change?
  • Related