使用Web Api,SignalR,MVC和OWIN进行Ninject

时间:2015-04-23 13:15:04

标签: asp.net signalr ninject asp.net-web-api owin

我在我的Web应用程序中使用了Ninject DI,其中包含来自Asp.Net堆栈(MVC,Web Api 2,SignalR)的一堆技术。

我已设法通过以下方法使DI适用于所有正在使用的技术:

public static class NinjectWebCommon 
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    internal static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();

        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);

        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        GlobalHost.DependencyResolver = new Microsoft.AspNet.SignalR.Ninject.NinjectDependencyResolver(kernel);
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));

        // Binding services here
    }        
}

到目前为止一切顺利。

这一切都与使用Global.asax初始化的Web Api有关。

现在我切换到OWIN管道。所以我从Global.asax中删除了GlobalConfiguration.Configure(WebApiConfig.Register);并添加了

HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);

到我的OwinStartup课程。 DI用于Web Api停止工作。

我开始搜索合适的解决方案并找到Ninject.Web.WebApi.OwinHost包。因此,为了使单个内核解决所有技术的依赖关系,我做了以下更改:

在OwinStartup中:

app.UseNinjectMiddleware(NinjectWebCommon.CreateKernel);
app.UseNinjectWebApi(config);
NinjectWebCommon中的

//[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(App.TradingServer.ConfiguratorApp.App_Start.NinjectWebCommon), "Start")]
//[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(App.TradingServer.ConfiguratorApp.App_Start.NinjectWebCommon), "Stop")]

禁用这些行以避免两次初始化内核。

此固定DI用于Web Api,但不适用于SignalR。当客户端尝试连接到集线器时,我得到以下异常:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.AspNet.SignalR.PersistentConnection.ProcessNegotiationRequest(HostContext context)
   at Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(HostContext context)
   at Microsoft.AspNet.SignalR.Hubs.HubDispatcher.ProcessRequest(HostContext context)
   at Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(IDictionary`2 environment)
   at Microsoft.AspNet.SignalR.Owin.Middleware.HubDispatcherMiddleware.Invoke(IOwinContext context)
   at Microsoft.Owin.Infrastructure.OwinMiddlewareTransition.Invoke(IDictionary`2 environment)
   at Microsoft.Owin.Mapping.MapMiddleware.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at System.Web.Http.Owin.HttpMessageHandlerAdapter.<InvokeCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Ninject.Web.Common.OwinHost.OwinBootstrapper.<Execute>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.<DoFinalWork>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow()
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) | RuntimeMethodInfo.UnsafeInvokeInternal => RuntimeMethodHandle.InvokeMethod => Application.Application_Error

我有点迷茫。我读了大约两十篇文章,但没有一篇给我解决方案。非常感谢任何帮助。

我的最终目标是拥有一个服务于Web Api,MVC和SignalR的内核,并支持OWIN管道。

编辑:由于我发表评论说我的案子可能与另一个问题重复,我认为我需要提供一些解释。

我有三种情况。

  1. 使用GlobalConfiguration.Configure(WebApiConfig.Register)在Global.asax中进行WebApi初始化,使用NinjectWebCommon和Bootstrapper进行Ninject初始化。

    这给了我注射WebApi和SignalR。但是,由于我想将WebApi初始化移动到OWIN启动,这种方法已经过时了。

  2. 使用OWIN启动进行WebApi初始化,使用NinjectWebCommon和Bootstrapper进行Ninject初始化。

    SignalR注入工作,WebApi注入不起作用。

  3. 使用OWIN启动进行WebApi初始化,使用UseNinjectMiddleware进行Ninject初始化,使用UseNinjectWebApi。

    WebApi注入工作,SignalR注入不起作用。

  4. 所以基本上我需要弄清楚如何把它放在一起,这样当我在OWIN管道上初始化WebApi时,WebApi和SignalR注入都会起作用。

    NinjectWebCommon的代码在下面是原始问题。它包含用于创建SignalR解析器的代码,但在方案3中没有帮助。

    编辑2:经过几个小时的试错法,我得出结论,打电话

    app.UseNinjectMiddleware(NinjectWebCommon.CreateKernel);
    app.UseNinjectWebApi(config);
    

    与此致电冲突:

    GlobalHost.DependencyResolver = new Microsoft.AspNet.SignalR.Ninject.NinjectDependencyResolver(kernel);
    

    所以问题描述对此缩小了。当我使用以下模式时,SignalR停止工作:

    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);
    
        app.UseNinjectMiddleware(CreateKernel);
        app.UseNinjectWebApi(config);
    
        GlobalHost.HubPipeline.AddModule(new GlobalSignalRExceptionHandler());
        app.MapSignalR();
    }
    
    
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
    
        GlobalHost.DependencyResolver = new Microsoft.AspNet.SignalR.Ninject.NinjectDependencyResolver(kernel);
        DependencyResolver.SetResolver(new Ninject.Web.Mvc.NinjectDependencyResolver(kernel));
    
        return kernel;
    }
    

    但如果我评论该行

        //GlobalHost.DependencyResolver = new Microsoft.AspNet.SignalR.Ninject.NinjectDependencyResolver(kernel);
    

    SignalR再次开始工作。但当然没有在集线器内注入。

3 个答案:

答案 0 :(得分:4)

最后,我设法获得了支持OWIN管道,WebApi,MVC和SignalR的工作Ninject配置。

当我发布问题时,我有一个解决方法(在SignalR集线器中禁用了DI),所以我决定不再浪费时间在这上面并继续前进。

但是当我尝试使用我的Startup类运行OWIN内存测试服务器时,发生DI无法正常工作。调用CreateKernel方法太晚了,导致创建了一个在sengleton范围内使用的对象的几个实例。

在使用不同的初始化变体后,我已经为OWIN测试服务器进行了DI工作,并且还修复了SignalR DependencyResolver。

解决方案:

我停止使用包 Ninject.Web.Common.OwinHost Ninject.Web.WebApi.OwinHost ,因此这些调用已从我的配置方法中删除:

//app.UseNinjectMiddleware(NinjectWebCommon.CreateKernel);
//app.UseNinjectWebApi(config);

相反,我会做以下事情:

public void Configuration(IAppBuilder app)
{
    ConfigureOAuth(app);

    HttpConfiguration config = new HttpConfiguration();
    WebApiConfig.Register(config);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

    NinjectWebCommon.Start();
    config.DependencyResolver = new NinjectDependencyResolver(NinjectWebCommon.bootstrapper.Kernel);
    app.UseWebApi(config);

    app.MapSignalR();
}

public static class NinjectWebCommon 
{
    private static bool _isStarted;

    internal static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start() 
    {
        // When creating OWIN TestService instances during unit tests
        // Start() method might be called several times
        // This check ensures that Ninject kernel is initialized only once per process
        if (_isStarted)
            return;

        _isStarted = true;

        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    internal static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        RegisterServices(kernel);
        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        // DI for SignalR
        GlobalHost.DependencyResolver = new Microsoft.AspNet.SignalR.Ninject.NinjectDependencyResolver(kernel);
        // DI for MVC
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));

        // Binding code here
        kernel.Bind<Something>().ToSelf().InSingletonScope();
    }        
}

答案 1 :(得分:1)

为了对WebApi和SignalR使用依赖项解析器,您需要实现一个如下所示的类:

    public class NinjectDependencyResolver : Microsoft.AspNet.SignalR.DefaultDependencyResolver,
    System.Web.Http.Dependencies.IDependencyResolver
{
    public readonly IKernel Kernel;

    public NinjectDependencyResolver(string moduleFilePattern)
        : base()
    {
        Kernel = new StandardKernel();
        Kernel.Load(moduleFilePattern);

    }
    public override object GetService(Type serviceType)
    {
        var service = Kernel.TryGet(serviceType) ?? base.GetService(serviceType);
        return service;
    }

    public override IEnumerable<object> GetServices(Type serviceType)
    {
        IEnumerable<object> services = Kernel.GetAll(serviceType).ToList();
        if (services.IsEmpty())
        {
            services = base.GetServices(serviceType) ?? services;
        }
        return services;
    }

    public System.Web.Http.Dependencies.IDependencyScope BeginScope()
    {
        return this;
    }

    public void Dispose()
    { }
}

然后在您的启动类中,您应该为WebApi和SignalR注册NinjectDependencyResolver,如下所示:

public void Configuration(IAppBuilder app)
{
    var dependencyResolver = new NinjectDependencyResolver("*.dll");

    var httpConfiguration = new HttpConfiguration();
    httpConfiguration.DependencyResolver = dependencyResolver;
    app.UseWebApi(httpConfiguration);

    var hubConfig = new HubConfiguration { Resolver = dependencyResolver };
    app.MapSignalR(hubConfig);
}

答案 2 :(得分:0)

SignalR必须在依赖注入配置之后配置。因此,在OWIN Startup类中,请确保在设置MVC依赖项解析器(func dateToUnix(date: String) -> Double { let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(abbreviation: "UTC") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-HH:mm" let utcDate = dateFormatter.date(from: date) guard let unixTime = utcDate?.timeIntervalSince1970 else { return 0.0 } return unixTime } ),WebApi依赖项解析器("startTime": "2018-07-10T01:00:00-05:00", "endTime": "2018-07-10T02:00:00-05:00", )之后,在 之后调用app.MapSignalR()和SignalR依赖解析器(System.Web.MVC.DependencyResolver)。