gpt4 book ai didi

c# - 无法在服务中注入(inject)依赖

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:20 29 4
gpt4 key购买 nike

我有一个看起来像这样的服务:

public class StuffService : ServiceStack.Service
{
private IStuffHandler _handler;

public StuffService(IStuffHandler handler)
{
_handler = handler;
}

public void Post(RequestMessage message)
{
_handler.HandleIt();
}
}

在 StuffService 中,_handler 应实例化为以下类:

public class StuffHandler : IStuffHandler
{
public void HandleIt()
{
//do stuff
}
}

在一个单独的文件中:

  public class ServiceAppHost : AppHostHttpListenerBase
{
public ServiceAppHost() :
base("CoolConnectionString", typeof(ServiceAppHost).Assembly)
{
}

public override void Configure(Container container)
{
this.Plugins.Add(new SwaggerFeature());
container.RegisterAs<IStuffHandler, StuffHandler>();
}
}

static void Main(string[] args)
{
ServiceAppHost appHost = new ServiceAppHost();
appHost.Init();
appHost.Start("http://localhost:7894/");
Console.Read();
}

现在,我不知道如何将 IStuffHandler 设置为 StuffHandler 的实例。我关注了this page在官方 ServiceStack 文档页面上。我在该链接页面上尝试了几种不同的方法,但我无法让 ServiceStack 将 _handler 实例化为 StuffHandler 实例。我需要做什么?

最佳答案

DependencyInjection 需要在某个地方可以注入(inject)依赖项 - 在您的情况下没有办法,要设置私有(private)字段。
您要么需要一个接受 IStuffHandler 的构造函数或您的 DI 容器支持的其他一些公共(public)方法/字段/属性。

在您的启动方法中,您将不得不调用类似于container.resolve<MyService>() 的方法。从容器中获取实例。

关于c# - 无法在服务中注入(inject)依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35413200/

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