如何使用通用 OwinCommunicationsListener 将依赖注入添加到无状态服务中

How to add Dependency Injection into a stateless service with a generic OwinCommunicationsListener

我在 Service Fabric 下有 7 个服务 运行。我决定创建一个通用的 OwinCommunicationsListener class 因为代码可以非常通用。

我注意到 Service Fabric 的模板将启动 class(配置管道)设置为静态 class,无状态服务 class 将其作为操作传递

    internal sealed class WebService : StatelessService
{
    public WebService(StatelessServiceContext context)
        : base(context)
    { }

    /// <summary>
    /// Optional override to create listeners (like tcp, http) for this service instance.
    /// </summary>
    /// <returns>The collection of listeners.</returns>
    protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        return new ServiceInstanceListener[]
        {
            new ServiceInstanceListener(serviceContext => new OwinCommunicationListener(Startup.ConfigureApp, serviceContext, ServiceEventSource.Current, "ServiceEndpoint"))
        };
    }
}

如果我需要做 DI,我需要将那些对象传递给启动 class。从模板中,我能看到的唯一方法是在 OwinCommunicationsListener 中设置这些对象或将参数传递给 OwinCommunicationsListener——这两种方法都意味着 OwinCommunicationsListener 不太通用。

我注意到在 WordCount 示例中,他们进行了正常启动 class 并将对它的引用传递给 OwinCommunicationsListenter。这样,ServiceClass 可以将一些对象传递给 Startup,它可以用于 DI,并且 OwinCommunicationsListener 可以保持通用。

    public class WordCountWebService : StatelessService
{
    public WordCountWebService(StatelessServiceContext context)
        : base(context)
    {
    }

    /// <summary>
    /// Creates a listener for Web API with websockets.
    /// </summary>
    /// <returns>The OWIN communication listener.</returns>
    protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        return new[]
        {
            new ServiceInstanceListener(initParams => new OwinCommunicationListener("wordcount", new Startup(MyDIObject), initParams))
        };
    }
}

如果我将无状态服务 class 视为大脑,将 OwinCommunicationsListener class 视为由多个服务共享的通用助手,那么我似乎应该采用与 wordcount 示例相同的路线,并且有一个非静态启动 class。这种方法有什么缺点吗?我想知道为什么模板不使用这种方法,因为微服务的想法是我们将拥有很多模板,而像这样的通用脚手架可以改善维护和可靠性。

wordcount 示例是我推荐的示例。没有我所知道的缺点。

你看过 ASP.NET Core 了吗?使用带有内置 DI 的 IWebHost,它变得更加容易。这是一个例子:https://github.com/vturecek/service-fabric-xray/blob/master/src/xray.Data/DataService.cs