gpt4 book ai didi

c# - 无法在 .NET Core 2.0 的启动构造函数中注入(inject)我自己的对象

转载 作者:太空狗 更新时间:2023-10-30 00:13:49 25 4
gpt4 key购买 nike

我正在尝试使用依赖注入(inject)来注入(inject)我自己的类,如下所示:

// Startup.cs
public class Startup
{
private readonly ILogger _log;
private readonly IMainController _controller;
public Startup(ILoggerFactory loggerFactory, IMainController controller)
{
_log = loggerFactory.CreateLogger("Logger");
_controller = controller;
}

// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IMainController, MainController>();
// services.AddTransient<MainController, MainController>();
}

然后是要注入(inject)的对象MainController

// MainController.cs
public interface IMainController
{
Task Run(HttpContext context);
}
public class MainController : IMainController
{
private readonly ILogger _log;

public MainController(ILoggerFactory loggerFactory)
{
_log = loggerFactory.CreateLogger("Logger");
}

在运行时,我收到以下错误:

Unhandled Exception: System.InvalidOperationException: Unable to resolve service for type 'mtss.ws.IMainController' while attempting to activate 'mtss.ws.Startup'. at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider) at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)

我想在 MainController 中注入(inject)一个 ILoggerFactory(就像它在 Startup 中所做的那样),然后在 Startup 中注入(inject)一个新创建的 MainController...

最佳答案

除了@nkosi 在https://stackoverflow.com/a/46013224/47633 回答,您还可以使用 WebHostBuilder ConfigureServices 方法添加依赖项,如文档中所述:

Any services added by the WebHostBuilder ConfigureServices method may be requested by the Startup class constructor or its Configure method. Use WebHostBuilder to provide any services you need during Startup methods.

应该是这样的

// ...other code removed for brevity
// in Program.cs
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureServices(services =>
services.AddScoped<IMainController, MainController>()
)
.UseStartup<Startup>()
.Build();

然后在 Startup.cs 中我可以执行以下操作

private readonly ILogger _log;
private readonly IMainController _controller;

public Startup(ILoggerFactory loggerFactory, IMainController controller)
{
_log = loggerFactory.CreateLogger("Logger");
_controller = controller;
}

gist帮我弄明白了,它有很多有用的例子

关于c# - 无法在 .NET Core 2.0 的启动构造函数中注入(inject)我自己的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46011176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com