Ninject从OnApplicationStarted注入​​依赖项

时间:2011-04-08 03:24:52

标签: asp.net-mvc asp.net-mvc-3 ninject

我正在使用Global.ascx.cs文件中的OnApplicationStarted中的服务。有没有办法依赖从那里注入存储库?

我的代码:

public class MvcApplication : NinjectHttpApplication
{
    //Need to dependency inject this.
    private IBootStrapService bootService;

    protected override void OnApplicationStarted()
    {
        //Used to set data such as user roles in database on a new app start.
        bootService.InitDatabase();

        base.OnApplicationStarted();

        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

    internal class SiteModule : NinjectModule
    {
        public override void Load()
        {
            //I set my bindings here.
            Bind<IBootStrapService>().To<BootStrapService>();
            Bind<IUserRepository>().To<SqlServerUserRepository>()
                .WithConstructorArgument("connectionStringName", "MyDb");
        }
    }
}

那么我如何让ninject在app开始时做DI?如您所见,我在SiteModule类中设置了绑定。

1 个答案:

答案 0 :(得分:1)

您可以覆盖注册模块的CreateKernel方法:

protected override IKernel CreateKernel()
{
    return new StandardKernel(
        new INinjectModule[] 
        { 
            new SiteModule()
        }
    );
}

但这不会自动注入bootService字段。您可以像这样实例化它:

protected override void OnApplicationStarted()
{
    base.OnApplicationStarted();

    //Used to set data such as user roles in database on a new app start.
    var bootService = Kernel.Get<IBootStrapService>();
    bootService.InitDatabase();

    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}