Reputation: 57469
I'm using a service from my OnApplicationStarted inside my Global.ascx.cs file. Is there a way to dependency inject the repository from there?
My code:
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");
}
}
}
So how do I get ninject to do DI right inside the app start? As you can see, I setup my bindings in the SiteModule
class.
Upvotes: 0
Views: 849
Reputation: 1038930
You could override the CreateKernel
method where you would register your modules:
protected override IKernel CreateKernel()
{
return new StandardKernel(
new INinjectModule[]
{
new SiteModule()
}
);
}
This will not automatically inject the bootService
field though. You could instantiate it like this:
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);
}
Upvotes: 1