使用 Autofac 和 IHostBuilder 解析服务

Posted

技术标签:

【中文标题】使用 Autofac 和 IHostBuilder 解析服务【英文标题】:Resolve service with Autofac and IHostBuilder 【发布时间】:2022-01-08 09:37:07 【问题描述】:

我有一个 MVVM wpf 应用程序,我正在尝试使用 Autofac 实现依赖注入。

App.xaml.cs:

public App()
    // getting config path here
    ...

    var config = new ConfigurationBuilder()
                   .SetBasePath(Directory.GetCurrentDirectory())
                   .AddJsonFile(configFilePath, optional: true, reloadOnChange: true)
                   .Build();

    // Host builder
    host = Host.CreateDefaultBuilder()
       .UseServiceProviderFactory(new AutofacServiceProviderFactory())
       .ConfigureContainer<ContainerBuilder>(builder =>
        
            builder.RegisterModule(new ConfigurationModule(config));
            builder.RegisterType<MyService>().As<IMyService>();
            builder.RegisterType<MainViewModel>().As<IMainViewModel>();
            builder.Register(c => c.Resolve<IHttpClientFactory>().CreateClient()).As<HttpClient>();
            _containerBuilder = builder;
        )
       .Build();

然后在应用启动时我想设置我的视图模型数据上下文

protected override async void OnStartup(StartupEventArgs e)
 
    await host.StartAsync();

    // How to get a reference to my container or scope here to be able to resolve IMainViewModel ?
    var container = ...
    var mainVM = container.Resolve<IMainViewModel>();
    var window = new MainWindow  DataContext = mainVM ;
    window.Show();

    base.OnStartup(e);


如何在 OnStartup 方法中解析我的 MainViewModel ?

【问题讨论】:

【参考方案1】:

来自IHost的服务提供者可用于解析主视图模型

using Microsoft.Extensions.DependencyInjection;

//...

protected override async void OnStartup(StartupEventArgs e)  
    await host.StartAsync();

    IServiceProvider services = host.Services;
            
    IMainViewModel mainVM = services.GetService<IMainViewModel>();

    var window = new MainWindow  DataContext = mainVM ;
    window.Show();

    base.OnStartup(e);


它将在后台调用 Autofac 容器。服务提供者只是 Autofac 容器之上的一个抽象,因为

.UseServiceProviderFactory(new AutofacServiceProviderFactory())

被调用。

【讨论】:

用你的建议得到这个:The non-generic method 'IServiceProvider.GetService(Type)' cannot be used with type arguments @Narthe 您很可能缺少用于依赖注入的using Microsoft.Extensions.DependencyInjection。泛型GetService&lt;&gt; 是一种扩展方法 即使我使用 Autofac 的依赖注入,我也应该这样做吗? using Autofac.Extensions.DependencyInjection; @Narthe 是的。它将调用引擎盖下的 autofac 容器。服务提供者只是 autofac 容器之上的一个抽象 谢谢,我对这两者感到困惑。

以上是关于使用 Autofac 和 IHostBuilder 解析服务的主要内容,如果未能解决你的问题,请参考以下文章

如何处理 IHostBuilder CreateHostBuilder 的异常

Autofac和nopcommerce中的Autofac, 还有反射

Autofac 和 Func 工厂

依赖注入容器Autofac的详解

Autofac IoC依赖注入容器的特点

使用 FluentNhibernate 和 Autofac 的映射接口