autofac owin wep api和signalr

时间:2016-05-11 10:29:28

标签: asp.net-web-api signalr autofac

我正在使用带有web api的autofac,现在我也想添加signalr。 我目前的配置如下

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        // Register your Web Api controllers.
        IoC.Instance.RegisterApiControllers(Assembly.GetExecutingAssembly());
        IoC.Instance.RegisterWebApiModelBinders(Assembly.GetExecutingAssembly());
        IoC.Instance.RegisterWebApiModelBinderProvider();

        //Set Autofac to be the Dependency Resolver both for Web Api and for SignalR
        config.DependencyResolver = new AutofacWebApiDependencyResolver(IoC.Instance.GetComponentsContainer());
        // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
        // and finally the standard Web API middleware.
        app.UseAutofacMiddleware(IoC.Instance.GetComponentsContainer());
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);
        //Signalr
        app.Map("/signalr", map =>
        {
            map.UseCors(CorsOptions.AllowAll);
            //   map.MapSignalR("/signalr", hubconfig);
            var hubConfiguration = new HubConfiguration
            {
            };
            map.RunSignalR(hubConfiguration);
        });

    }
}

IoC Class如下

public class IoC : ContainerBuilder
{
    private readonly static IoC _instance = new IoC();
    private static object _lock;
    private IContainer _componentsContainer;
    public static IoC Instance
    {
        get
        {
            return _instance;
        }
    }
    public IContainer GetComponentsContainer()
    {
        if (_componentsContainer == null)
        {
            lock (_lock)
            {
                if (_componentsContainer == null)
                    _componentsContainer = this.Build();
            }
        }
        return _componentsContainer;
    }
    public T Resolve<T>() where T : class
    {
        return GetComponentsContainer().Resolve<T>();
    }
    public ILifetimeScope BeginLifetimeScope()
    {
        return GetComponentsContainer().BeginLifetimeScope();
    }
    private IoC()
    {
        _lock = new object();
        ConfigureDependencies();
    }

    private void ConfigureDependencies()
    {
        var connectionString = ConfigurationManager.ConnectionStrings["DBConnectionStringName"].ConnectionString;
        this.Register(c => new SqlConnection(connectionString)).As<IDbConnection>().InstancePerRequest();// InstancePerLifetimeScope();

        //Database Connection OrmLite
        OrmLiteConfig.DialectProvider = SqlServerDialect.Provider;
        //Register Repositories
        this.RegisterType<Repository>().As<IRepository>().InstancePerRequest();//.InstancePerLifetimeScope();
        // Register Services
        this.RegisterType<UserService>().As<IUserService>().InstancePerRequest();//.InstancePerLifetimeScope();
        this.RegisterType<TokenService>().As<ITokenService>().InstancePerRequest();//.InstancePerLifetimeScope();
    }

}

很明显,我没有为SignalR添加依赖注入。我想补充一下 为了拥有像这样的集线器构造器

private readonly ITokenService _tokenService;
    private readonly ILifetimeScope _hubLifetimeScope;



    public JobHub(ILifetimeScope lifetimeScope)
    {
        // Create a lifetime scope for the hub.
        _hubLifetimeScope = lifetimeScope.BeginLifetimeScope();
        // Resolve dependencies from the hub lifetime scope.
        _tokenService = _hubLifetimeScope.Resolve<ITokenService>();
    }

关于如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:2)

经过一番调查后,我找到了解决方案。 在IoC类和方法ConfigureDependencies()中,我在末尾this.RegisterHubs(Assembly.GetExecutingAssembly());添加了以下行。 StartUp中的Configuration方法现在如下

   public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
        // Get your HttpConfiguration. In OWIN, you'll create one
        // rather than using GlobalConfiguration.

        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        //HubConfiguration
        var hubconfig = new HubConfiguration();
        // Register your Web Api controllers.
        IoC.Instance.RegisterApiControllers(Assembly.GetExecutingAssembly());
        IoC.Instance.RegisterWebApiModelBinders(Assembly.GetExecutingAssembly());
        IoC.Instance.RegisterWebApiModelBinderProvider();

        //Set Autofac to be the Dependency Resolver both for Web Api and for SignalR
        config.DependencyResolver = new AutofacWebApiDependencyResolver(IoC.Instance.GetComponentsContainer());
        hubconfig.Resolver = new AutofacDependencyResolver(IoC.Instance.GetComponentsContainer());
        // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
        // and finally the standard Web API middleware.
        app.UseAutofacMiddleware(IoC.Instance.GetComponentsContainer());
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);
        //Signalr
        app.Map("/signalr", map =>
        {
            map.UseCors(CorsOptions.AllowAll);
            map.RunSignalR(hubconfig);
        });

    }

现在是棘手的事情 我的中心构造函数必须像这样

 public JobHub(ILifetimeScope lifetimeScope)
    {
        // Create a lifetime scope for the hub.
        _hubLifetimeScope = lifetimeScope.BeginLifetimeScope("AutofacWebRequest");
        // Resolve dependencies from the hub lifetime scope.
        _tokenService = _hubLifetimeScope.Resolve<ITokenService>();
    }

我不知道那件事是如何起作用的,但它起作用了。欢迎任何关于配置是好还是坏的建议!

答案 1 :(得分:1)

在自定义集成之前,您的Startup.cs应如下所示

  public class Startup
  {
    public void Configuration(IAppBuilder app)
    {
      var builder = new ContainerBuilder();
      var config = new HubConfiguration();

      // Register your SignalR hubs.
      builder.RegisterHubs(Assembly.GetExecutingAssembly());

      // Set the dependency resolver to be Autofac.
      var container = builder.Build();
      config.Resolver = new AutofacDependencyResolver(container);

      app.UseAutofacMiddleware(container);
      app.MapSignalR("/signalr", config);
    }
  }

查看Autofacs网站上的文档了解更多信息: http://docs.autofac.org/en/latest/integration/signalr.html#owin-integration