Pergunta

I'm trying to wrap my head around dependency injection in the Onion Architecture, I've found this solution which uses a dependency resolution layer around the onion. But there is so much going on that I'm completely lost.

So I setup a project to try it out. I like to start off simple, so a simple log entry on a (MVC) controller method would be a good start. I'd like to use Dynamic Module Loading (kernel.Load("*.dll");) since it comes recommended from the Ninject wiki.

My solution looks like this: (For now)

Solution
- Core.Services
- Infrastructure.Logging
- DependencyResolution
- UI.MVC (default internet template)

I'd like to follow the guides lines for dependency resolution outlined here.

enter image description here

Ilogger

namespace Core.Services
{
    public interface ILogger
    {
        void Log(string message);
    }
}

Logging Implementation

namespace Infrastructure.Logging
{
    public class DebugLogger : ILogger
    {
        public void Log(string message)
        {
            Debug.WriteLine(message);
        }
    }
}

Dependency Resolution

namespace DependencyResolution
{
    public class TestModule : NinjectModule
    {
        public override void Load()
        {
            Bind<ILogger>().To<DebugLogger>();
        }
    }
}

What I want to accomplish

UI

namespace UI.MVC.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger _logger;

        public HomeController(ILogger logger)
        {
            _logger = logger;
        }

        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            _logger.Log("It works!");

            return View();
        }
    }
}

I need to run kernel.Load("*.dll"); somehow and I need to setup my MVC to use DI. I'm just now sure how since the UI cannot know about the Dependency Resolution layer.

Foi útil?

Solução

Your DI container should be composed somewhere. This place is called the composition root and is the outermost layer. In your case that would be the ASP.NET MVC application. So saying that it should not know about the DI simply doesn't make sense. The Ninject.MVC3 package comes with a custom dependency resolver implementation that gets plugged into the application and you will get automatic DI in your controllers.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top