本文介绍了检索 Autofac 容器以解析服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# WindowForms 应用程序中,我启动了一个 OWIN WebApp,它创建了我的另一个类 Erp 的单例实例:

In a C# WindowForms application I start an OWIN WebApp that creates a singleton instance of my other class Erp:

public partial class Engine : Form
{
    const string url = "http://*:8080"; //49396
    private IDisposable webApp;

    public Engine()
    {
        InitializeComponent();
        StartServer();
    }

    private void StartServer()
    {
        webApp = WebApp.Start<Startup>(url);
        Debug.WriteLine("Server started at " + url);
    }

    private void btnDoSomething(object sender, System.EventArgs e)
    {
       // needs to call a method in erp
    }
}

class Startup
{
    public void Configuration(IAppBuilder app)
    {
        Trace.Listeners.Remove("HostingTraceListener");
        app.UseCors(CorsOptions.AllowAll);

        var builder = new ContainerBuilder();
        var config = new HubConfiguration();
        builder.RegisterHubs(Assembly.GetExecutingAssembly()).PropertiesAutowired();
        var erp = new Erp();
        builder.RegisterInstance<Erp>(erp).SingleInstance();
        var container = builder.Build();
        config.Resolver = new AutofacDependencyResolver(container);
        app.UseAutofacMiddleware(container);
        app.MapSignalR(config);
    }
}

在创建 WebApp 之后,我想在代码的其他部分(即在上面的按钮事件处理程序中)检索创建的单例 erp 实例.

After the creation of the WebApp I want to retrieve in other part of my code (i.e. in the button's event handler above) the singleton erp instance created.

据我所知,我需要使用解析功能:

As far as I understand I need to use the resolve function:

var erp = container.Resolve<Erp>();

但我不清楚如何在配置函数之外检索container.

but it's not clear to me how to retrieve the container outside the Configuration function.

推荐答案

我不会想太多.在某处设置一个静态变量并保留它.

I wouldn't overthink it. Set a static variable somewhere and just hold onto it.

public static class ContainerProvider
{
  public static IContainer Container { get; set; }
}

在启动块中:

var container = builder.Build();
ContainerProvider.Container = container;
config.Resolver = new AutofacDependencyResolver(container);

现在您可以随时随地获取容器.

Now you can get the container wherever you need it.

这篇关于检索 Autofac 容器以解析服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:41
查看更多