开发者

ASP.Net MVC, Ninject IOC

I'm using Ninject to do some dependancy injection. (Mainly for the DAL), my project consists of 3 aspects and are as follows,

  1. Project.Lib (Everything database, services and anythign else that is logic)
  2. Project.Admin (Administration)
  3. Project.Web (Front end what the user see's)

Now, each of my controllers within my projects inherit from a BaseController

 public abstract class BaseController : Controller
    {
        protected BaseController(ISession session)
        {
            _Session = session;
        }

        public ISession _Session { get; private set; }
    }

And then and example controller might be like so,

 public class ImageController : BaseController
    {
        private MediaService _mediaService;

        public ImageController(ISession session) : base(session)
        {
            _mediaService = new MediaService(session);
        }

        [HttpGet]
        public ActionResult List()
    开发者_如何学Go    {   
            var RetVal = _mediaService.GetAllImages();
            return View(RetVal);
        }
}

As you can see the "Session" is passed from the controller to the service layer. I'm curious as to if this is good practie? ANy negitives to what we are doing here?


I'd avoid referencing ISession through your controller. A better solution would be to use Ninject to inject your services into your controllers. In this instance you'll need to create an abstraction for your MediaService class e.g.:

public interface IMediaService 
{
    SomeCollection GetAllImages();
    // ...
}

You'd then use Ninject to supply an implementation of the above interface to your controller:

public class ImageController : BaseController
{
    private IMediaService _mediaService;

    public ImageController(IMediaService mediaService)
    {
        _mediaService = mediaService
    }

    [HttpGet]
    public ActionResult List()
    {   
        var RetVal = _mediaService.GetAllImages();
        return View(RetVal);
    }

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜