已经发布了几个关于依赖注入的具体问题的问题,例如何时使用它以及它有哪些框架.然而,
什么是依赖注入以及何时/为什么应该或不应该使用它?
language-agnostic design-patterns dependency-injection terminology
如何使用ASP.NET Core MVC内置依赖注入框架手动解析类型?
设置容器很容易:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddTransient<ISomeService, SomeConcreteService>();
}
Run Code Online (Sandbox Code Playgroud)
但是如何在ISomeService不进行注射的情况下解决?例如,我想这样做:
ISomeService service = services.Resolve<ISomeService>();
Run Code Online (Sandbox Code Playgroud)
没有这样的方法IServiceCollection.
您知道如何手动解决.net core 中的依赖项吗?就像是
DependencyResolver.Resolve<ISomeService>()
Run Code Online (Sandbox Code Playgroud)
更新 我在一个没有注入的类中,我想从内部解决它,而不是到处传递变量