自定义角色提供者使用DI ninject投掷错误 [英] Custom Role Provider using DI ninject throwing error

查看:96
本文介绍了自定义角色提供者使用DI ninject投掷错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置一个CustomRoleProver为:

I setup a CustomRoleProver as:

public class CustomRoleProvider : RoleProvider
    {
        private readonly IRepository<User> _repository;

        public CustomRoleProvider(IRepository<User> repository)
        {
            _repository = repository;
        }

...

在我的Global.asax .cs我有:

In my Global.asax.cs I have:

//Create Ninject DI kernel
            var kernel = new StandardKernel();

            kernel.Bind<IRepository<User>>().To<Repository<User>>();

            //Tell ASP.NET MVC 3 to use our Ninject DI Container
            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));

当我尝试运行我的代码时,我得到:

When I try to run my code I get:

配置错误
说明:在处理此请求所需的配置文件时发生错误。请查看下面的具体错误详细信息,并正确修改配置文件。

Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

解析器错误消息:为此对象定义的无参数构造函数。

Parser Error Message: No parameterless constructor defined for this object.

来源错误:

第64行:
第65行:
第66行:
第67行:
第68行:

Line 64: Line 65: Line 66: Line 67: Line 68:

所以也许我对DI和njectject的理解完全不正确。我想,当它试图实例化CustomRoleProvider它将创建用户存储库并将其传递给构造函数,而不是尝试使用无参数的。

So maybe I have a totally incorrect understanding of DI and ninject. I thought that when it tried to instantiate teh CustomRoleProvider it would create the user repository and pass it to the constructor not trying to use a parameterless one.

我不明白这个是不正确的或者是我的设置不正确?

Do I understand this incorrectly or is my setup just incorrect?

我觉得这很奇怪,因为DI似乎主要用于控制器。

I find this strange because the DI seems to be mostly working for the controllers.

推荐答案

您正在撰写一个角色提供者,但目前尚不了解DI。 MVC中的很多类都是DI,这就是为什么你看到它与控制器一起工作。

You're writing a roleprovider, but these are not currently DI aware. A lot of the classes in MVC are DI aware, which is why you see it workign with controllers.

为了能够注入构造函数参数,DI容器必须负责创建您希望注入的对象。只需注册一个类型就不会使它可以定位。

To be able to inject a constructor parameter the DI container has to be responsible for creating the object you're hoping to inject into. Just registering a type does not magically make it locatable.

使用roleproviders,框架中的Roles类可以创建提供程序的实例,包括您的自定义提供程序。它只适用于无参数构造函数。您需要在自定义提供程序中使用属性注入,并使用Roles.Provider获取实例来注入您的依赖项。

With roleproviders, it is the Roles class within the framework that create instances of the providers, including your custom provider. It only works parameterless constructors. You'll need to use something like property injection within your custom provider and use Roles.Provider to get the instance to inject your dependencies into.

这篇关于自定义角色提供者使用DI ninject投掷错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆