开发者

.Net MVC 3 with Ninject and the [Inject] attribute configuration

i replaced the HttpAplication inheritance in my Global.asax to NinjectHttpApplication:

public class Global : NinjectHttpApplication
{
    protected override IKernel CreateKernel()
    {
        return Bootstrapper.CreateKernel();
    }

    protected override void OnApplicationStarted()
    {
        base.OnAp开发者_运维百科plicationStarted();
        DependencyResolver.SetResolver(new NinjectDependencyResolver(CreateKernel()));
        Bootstrapper.Bootstrap();
    }
}

And my CreateKernel method:

public static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    kernel.Load(Assembly.GetExecutingAssembly());
    return kernel;
}

I need to use the [Inject] attribute in my RoleService that use RoleProvider and is started by asp.net.

All say that if I inherit from NinjectHttpApplication in my Global.asax I don't need that line: DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel)); in my OnApplicationStarted method, but without that a exception is thrown and my dependency is NULL in my RoleProvider Service.

After all, I need that line or not? Am I doing something wrong?


The DependencyResolver is set by the extension during startup. If the service is created before ApplicationStart then the default one will be used. From your code I cant tell when it gets created. But normally this line shouldn't be required.

You can also try to use the NuGet way to integrate Ninject. This will start the Ninject Kernel and DependencyResolver a bit earlier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜