In ASP.NET MVC 5 is possible to obtain some dependency through DependencyResolver.Current.GetService<T>()
. Is there something similar in ASP.NET Core?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
There are extension methods for IServiceProvider: GetService, GetRequiredService and GetServices. All have generic and non-generic versions. In Asp.Net Core web project you can obtain reference to IServiceProvider via DI or from IApplicationBuilder. In Console app you should create your own instance of IServiceProvider and store reference somewhere
Yes, there is. In ASP.NET Core 1.0.0, the services available within a request from
HttpContext
are exposed through the RequestServices collection[1]:You can use the GetService method to retrieve the dependencies by specifying the type of the dependency:
Generally, you shouldn’t use these properties directly, preferring instead to request the types your classes you require via your class’s constructor, and letting the framework inject these dependencies. This yields classes that are easier to test and are more loosely coupled.
[1] https://docs.asp.net/en/latest/fundamentals/dependency-injection.html#request-services
Service available in Asp.net core, its within
HttpContext
By using this service, it is possible to get service. and also you can use GetService method to retrieve the dependencies by specifying the type of the dependency:
If you really need it, you can write own one. First - create
AppDependencyResolver
class.Please note that
_serviceProvider.GetService<T>();
only available if you addusing Microsoft.Extensions.DependencyInjection;
. That namespace will be available if you add"Microsoft.Extensions.DependencyInjection": "1.0.0"
to yourproject.json
. Than you should callInit
method in yourstartup
class. For exampleAfter that you can use it anywhere, same as
DependencyResolver.Current
. But my suggestion - use it only if no other choice left.I think this could be a good start:
That's official documentation for dependency injection for asp.net 5.
Dependency injection is now built into asp.net 5 but you are free to use other libraries like autofac. The default one is working fine for me.
In your starup class, you have a method like this
From:
DependencyResolver Asp.net 5.0
Here is the way that worked for me in .Net core 2.0
If I have to do it with classical way, It would be like below.