Paul
Paul

Reputation: 1620

Dependency injection solution architecture

After abstracting away different layers of my solution into separate projects (e.g. DataAccess, BusinessLogic, ApplicationService, UserInterface (ASP.NET MVC)) and enforcing that an upper layers only have reference to 1 layer lower to ensure no call from an upper layer can circumvent this architecture, I attempted to introduce constructor injection (using Unity) into my current project.

I'm not as happy as I thought I'd be with the results and am hoping there's a better approach.

I'm not happy that way up in the Global.asax of my UI layer, in order to build up the container I must reference every single project from every single layer all the way down to the Data Access repositories. This just feels wrong since now the multilayered design can be easily circumvented.

What approaches do you take to avoid this? Do you create a separate project for dependency injection and let that project reference everything? Then the UI layer only needs reference to the dependency injection project?

Is there a better way of accomplishing this?

Thanks in advance for your advice!

Upvotes: 1

Views: 323

Answers (1)

jgauffin
jgauffin

Reputation: 101150

This just feels wrong since now the multilayered design can be easily circumvented

Well. You can always circumvent that. You can also hack your code (or any other programmers that got access to it). You can introduce bugs. You can skip layers and use EF directly in the UI layer.

But you won't, since that's bad practice.

However, you can skip those references by using reflection (load the assemblies at runtime). The problem with that is that the other assemblies will not be automatically included in setup projects or when you publish your project.

If that's not a problem and you want to get everything done automagically: Use my container. It let's you have a composition root in each project. Then just load all other assemblies by doing this in the UI layer:

public void Application_Start(string[] args)
{
    var registrar = new ContainerRegistrar();

    // will load all modules from all assemblies which starts with "MyApp."
    registrar.RegisterModules(Environment.CurrentDirectory, "MyApp.*.dll");

    var container = registrar.Build();
}

More detailed explanation:

http://www.codeproject.com/Articles/440665/Having-fun-with-Griffin-Container

Upvotes: 1

Related Questions