Referencing Ninject in class library in ASP.NET MVC 3 application

前端 未结 2 1652
轮回少年
轮回少年 2021-01-20 00:08

I have an ASP.NET MVC 3 application that uses the Ninject.MVC3 extension to setup DI in my MVC application. Namely, there\'s the NinjectMVC3.cs file in the

相关标签:
2条回答
  • 2021-01-20 00:54

    You should be able to do this with constructor injection, like this:

    private readonly IEmailServices _emailServices;
    
    public UserServices(IEmailServices emailServices)
    {
        _emailServices = emailServices;
    }
    

    The service injection into your controllers should be handled automatically by the Ninject custom controller factory, which'll use the configured IoC container to resolve the IUserServices object when the controller is created, which will in turn be given an IEmailServices object by the container:

    public class MyController : Controller
    {
        private readonly IUserServices _userServices;
    
        public MyController(IUserServices userServices)
        {
            _userServices = userServices;
        }
    }
    

    When you're unit testing, you can manually inject a fake or mock email service into the user service.

    0 讨论(0)
  • 2021-01-20 01:06

    If you are using MVC 3 anyway, how about registering Ninject with the built-in DependencyResolver?

    System.Web.Mvc.DependencyResolver.SetResolver(yourKernel);
    

    Then, you can just use

    var svc = System.Web.Mvc.DependencyResolver.Current.GetService<bla>();
    

    where you need it. I don't know off hand if SetResolver accepts the Ninject Kernel directly or if you need a wrapper class, but I'd consider that the cleanest solution.

    0 讨论(0)
提交回复
热议问题