在.net中使用ninject ioc实例化类



我使用Ninject在我的ASP中做一些IoC。. NET MVC应用程序。

我有一个接口" isservice .cs":

public interface IService
{
    string method();
}

我有相应的实现"Service.cs":

public class Service
{
    string method()
    {
        return "result";
    }
}

我已经在另一个继承了NinjectModule的类中完成了绑定:

public class MyNinjectModule : NinjectModule
{
    public override void Load()
    {
        RegisterServices();
    }
    private void RegisterServices()
    {
        Kernel.Bind<IService>().To<Service>();
    }
}

我的类A使用这个服务:

public class A
{
    private readonly IService _service;
    private int i;
    public A(IService service, int i)
    {
        this._service=service;
        this.i=i;
    }        
}

问题是,现在,我不知道如何实例化我的类A在我的应用程序。这就是我卡住的地方,我怎么能调用Ninject告诉我的应用程序去获取接口的实现:

var myClass=new A(????) 

主要问题是你的Service类没有实现IService

public class Service
{
    string method()
    {
        return "result";
    }
}

应该是

public class Service : IService
{
    public string method()
    {
        return "result";
    }
}

但是对于实例化类,最好的方法是使用组合根来构建对象图。在MVC中,最好通过实现IControllerFactory来处理。

public class NinjectControllerFactory : DefaultControllerFactory
{
    private readonly IKernel kernel;
    public NinjectControllerFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return controllerType == null
                   ? null
                   : (IController)this.kernel.Get(controllerType);
    }
}
使用

using System;
using Ninject;
using DI;
using DI.Ninject;
using DI.Ninject.Modules;
internal class CompositionRoot
{
    public static void Compose()
    {
        // Create the DI container
        var container = new StandardKernel();
        // Setup configuration of DI
        container.Load(new MyNinjectModule());
        // Register our ControllerFactory with MVC
        ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(container));
    }
}

Application_Start中,添加:

CompositionRoot.Compose();

您还需要为您的类A创建一个接口并注册它。整数不能自动解析,必须显式地解析。

Kernel.Bind<IClassA>().To<A>()
    .WithConstructorArgument("i", 12345);

然后你会添加你的依赖到一个控制器。依赖项的依赖项会自动解析。

public class HomeController : Controller
{
    private readonly IClassA classA;
    public HomeController(IClassA classA)
    {
        if (classA == null)
            throw new ArgumentNullException("classA");
        this.classA = classA;
    }
    public ActionResult Index()
    {
        // Use this.classA here...
        // IService will be automatically injected to it.
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
        return View();
    }
}

最新更新