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

前端 未结 2 1651
轮回少年
轮回少年 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.

提交回复
热议问题