如何使用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.
我正在使用 ASP.NET Core Web API。我很难实例化一个使用 DI 的非控制器类。有很多与此相关的文章,但没有一篇文章回答了我的问题(据我所知)。这些是最受欢迎和相关的:
我的用例(一个人为的例子):
我有一个类SpeechWriter依赖于IRandomTextService:
public class SpeechWriter
{
private readonly IRandomTextService _textService;
// Constructor with Text Service DI
public SpeechWriter(IRandomTextService textService)
{
_textService = textService;
}
public string WriteSpeech()
{
var speech = _textService.GetText(new Random().Next(5,50));
return speech;
}
}
Run Code Online (Sandbox Code Playgroud)
IRandomTextService界面:
public interface IRandomTextService
{
public string GetText(int wordCount);
}
Run Code Online (Sandbox Code Playgroud)
和实施:
public class RandomTextService : IRandomTextService
{
public string GetText(int wordCount)
{ …Run Code Online (Sandbox Code Playgroud) 我正在使用ASP.NET Core,我知道框架已经提供了这样的Logging机制,但是使用它来说明我的问题.
我正在使用一种Factory模式来构建Logger类,因为我不知道日志记录的类型(因为它存储在DB中).
ILogger合同
Log(string msg)
Run Code Online (Sandbox Code Playgroud)
然后,在根据从DB传递的参数创建Logger之后,LoggerFactory将返回ILogger:
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
Run Code Online (Sandbox Code Playgroud)
现在,当我需要使用Logger时,我必须这样做:
public class MyService
{
private ILogger _logger
public MyService()
{
_logger = LoggerFactory.BuildLogger("myType");
}
Run Code Online (Sandbox Code Playgroud)
但是,我打算在没有任何实例化的情况下保留我的类,我需要在MyService中使用Constructor DI,我需要在Startup上注入所有依赖项:
services.AddTransient<Contracts.ILogger, LoggerFactory.BuildLogger("param") > ();
Run Code Online (Sandbox Code Playgroud)
但这不起作用,我们需要通过一个具体的实现.如何使用DI来完成这项工作,是否有更好的方法来实现它?
c# asp.net-mvc dependency-injection factory-pattern asp.net-core