如何在IWebHost上使用Autofac

问题描述

我有一个在Service Fabric中运行的AspNet Core Web应用程序(DotNetCore 3.1)。 您可能知道,Service Fabric使Program.cs和Startup.cs有点特殊。

在任何情况下,它对于Microsoft Dependency Injection都可以完美运行,但是当我尝试使用Autofac对其进行配置时,通过查看文档或使用Google搜索似乎无法成功。

添加Autofac.Extensions.DependencyInjection nuget程序包,它允许我执行以下操作:

Host.CreateDefaultBuilder(args).UseServiceProviderFactory(new AutofacServiceProviderFactory());

但是,我的Sateless服务结构Web Api项目中包含以下内容

/// <summary>
/// The FabricRuntime creates an instance of this class for each service type instance. 
/// </summary>
internal sealed class SampleStatelessWebApi : StatelessService
{
    public SampleStatelessWebApi(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()
    {
        var serviceInstanceListeners = new ServiceInstanceListener[]
        {
            new ServiceInstanceListener(serviceContext =>
                new KestrelCommunicationListener(serviceContext,"ServiceEndpoint",(url,listener) =>
                {
                    ServiceEventSource.Current.ServiceMessage(serviceContext,$"Starting Kestrel on {url}");

                    return new WebHostBuilder()
                                .UseKestrel()
                                .UseCommonConfiguration()
                                .ConfigureServices(
                                    services => services
                                        .AddSingleton<StatelessServiceContext>(serviceContext))
                                .UseContentRoot(Directory.GetCurrentDirectory())
                                .UseStartup<Startup>()
                                .UseServiceFabricIntegration(listener,ServiceFabricIntegrationoptions.None)
                                .UseUrls(url)
                                .Build();
                }))
        };
        return serviceInstanceListeners;
    }
}

和我用于集成测试的TestServer如下:

var server =
    new TestServer(
        new WebHostBuilder()
            .UseStartup<Startup>()
            .UseCommonConfiguration()
            .UseEnvironment("Test")
            .ConfigureTestServices(ConfigureTestServices));

换句话说,我有一个WebHostBuilder,而不是主机。

See my sample working without Autofac。我只需要能够向其中添加Autofac支持

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...