c# - 检索 Autofac 容器以解析服务

标签 c# owin autofac

在 C# WindowForms 应用程序中,我启动了一个 OWIN WebApp,它创建了我的其他类 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 实例。

据我所知,我需要使用 resolve 函数:

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

但我不清楚如何在 Configuration 函数之外检索 container

最佳答案

我不会想太多。在某处设置一个静态变量并保持不变。

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

在 Startup 的代码块中:

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

现在您可以在任何需要的地方获取容器。

关于c# - 检索 Autofac 容器以解析服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48216003/

相关文章:

c# - 使用 Autofac 注册 IReliableStateManagerReplica

c# - 使用动态类型

c# - 在 .Net 2.0 中写入和读取 XML 文件中的二进制数据

c# - 带有 Microsoft Fakes 的 Stub 或 Shim Process 类

azure - 使用 AD 保护 Azure API 管理中的所有 API

c# - 添加新组件会删除所有组件的现有注册

C# Enum 使用 Sql Server 表中的值

visual-studio-2013 - 将 Scope "wl.emails"添加到 Startup.Auth.cs 中的 MicrosoftAccountAuthenticationOptions 会导致问题

ASP.NET MVC 5 Web.config : "FormsAuthenticationModule" or "FormsAuthentication"

autofac - Meta<T, TMetadata> 在 Autofac 3+ 中损坏?