簡體   English   中英

Ninject和依賴注入WebApi屬性

[英]Ninject and Dependency Injection WebApi Attributes

我使用Ninject:

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>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        var resolver = new NinjectSignalRDependencyResolver(kernel);
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            GlobalHost.DependencyResolver = new NinjectSignalRDependencyResolver(kernel);

            RegisterServices(kernel);

            GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);

            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<TMS.Entities.AssetContext>().ToSelf().InRequestScope();
        kernel.Bind<TMS.Data.IDbContext>().To<TMS.Entities.AssetContext>().InRequestScope();
        kernel.Bind(typeof(TMS.Data.IRepository<>)).To(typeof(TMS.Data.EfRepository<>));

        kernel.Bind<IExportManager>().To<ExportManager>().InRequestScope();
        kernel.Bind<IDriverService>().To<Services.Drivers.DriverService>().InRequestScope();
        .....
    }
}

它適用於Mvc和Api控制器。 但是現在我正在編寫ActionFilter:

public class AccessLoadApiAttribute : ActionFilterAttribute
{
    public AccessLoadApiAttribute()
    {

    }

    private readonly ILoadServiceEntity _loadServiceEntity;
    public AccessLoadApiAttribute(ILoadServiceEntity loadServiceEntity)
    {
        _loadServiceEntity = loadServiceEntity ?? throw new ArgumentNullException(nameof(loadServiceEntity));
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var loadId = Convert.ToInt32(actionContext.RequestContext.RouteData.Values["Id"]);
        _loadServiceEntity.GetLoadById(loadId);

        base.OnActionExecuting(actionContext);
    }
}

_loadServiceEntity為null。 配置有什么問題?

在Asp.Net Web API 2.x中,如果要在單個操作上使用屬性,則屬性不允許通過構造函數進行依賴項注入。

你將不得不通過使用該服務定位器反模式IDependencyResolver可以通過訪問HttpConfiguration

例如

public class AccessLoadApiAttribute : ActionFilterAttribute {

    public override void OnActionExecuting(HttpActionContext actionContext) {
        //get the resolver via the request context
        var resolver = actionContext.RequestContext.Configuration.DependencyResolver;
        //use resolver to get dependency
        ILoadServiceEntity _loadServiceEntity = (ILoadServiceEntity)resolver.GetService(typeof(ILoadServiceEntity));
        var loadId = Convert.ToInt32(actionContext.RequestContext.RouteData.Values["Id"]);
        _loadServiceEntity.GetLoadById(loadId);
        base.OnActionExecuting(actionContext);
    }
}

現在可以根據需要使用該屬性

[AccessLoadApi]
[HttpGet]
public IHttpActionResult SomeGetAction() {
    return Ok();    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM