简体   繁体   English

Ninject属性或构造注入ASP.NET MVC3

[英]Ninject property or construction inject ASP.NET MVC3

I'm using Ninject.MVC3. 我正在使用Ninject.MVC3。

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<Repository>().To<Repository>();
}       

Registering them like so in the App_Start. 在App_Start中注册它们就像这样。 It works just fine on controller that request this repository. 它在请求此存储库的控制器上工作正常。 However I also have a few classes that need this repository. 但是我也有一些需要这个存储库的类。

        [Inject]
        public MemberShipService(Repository repository)
        {
            this.Repository = repository;
        }

^Example from a class constructor. ^类构造函数的示例。 I've tried constructor injection this simply gives me errors because it requests an argument for the constructor. 我试过构造函数注入这只是给我错误,因为它请求构造函数的参数。 Property injection simply doesn't work. 物业注入根本不起作用。

Do I need to do something extra to make constructor or property injection work in asp.net mvc3? 我是否需要做一些额外的工作才能在asp.net mvc3中进行构造函数或属性注入? I haven't done any other configuration inside NinjectWebCommon other then the line I posted above. 我没有在NinjectWebCommon中做任何其他配置,除了我上面发布的那一行。

You'll need to resolve an instance of the class using dependency resolver in order to use it, create an instance of your MemberShipService using: 您需要使用依赖项解析程序解析类的实例才能使用它,使用以下命令创建MemberShipService的实例:

var memberShipService = 
    DependencyResolver.Current.GetService(typeof(MemberShipService)) as MemberShipService;

That will bind your instance variable Repository using your constructor that you specified. 这将使用您指定的构造函数绑定您的实例变量Repository

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM