我正在使用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
类中设置了绑定。
答案 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);
}