【问题标题】:Resolve service with Autofac and IHostBuilder使用 Autofac 和 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 ?

【问题讨论】:

    标签: c# wpf .net-core autofac


    【解决方案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 容器之上的一个抽象
    • 谢谢,我对这两者感到困惑。
    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    相关资源
    最近更新 更多