Dependency inversion - owner of interfaces? - asp.net-mvc

I am starting with ASP.NET MVC and trying to learn DI and dependency inversion at the same time. I am setting up at MVC project where the controllers and views reside in one assembly and I also have a couple of more assemblies for domain models and services that to most of the actual business logic.
The plan is to have all my services implement interfaces. The controllers that call the services access them through these interfaces. Instantiation is done using the Ninject DI framework.
Now the actual question; who "owns" the interfaces? From my understanding of dependency inversion, the service interfaces would be owned by the controllers and therefore reside in that assembly.

None of your components have to own the interfaces. Good interfaces are their own animal - they just have to be visible to both the controllers and services.
Physically segregating them creates headaches that may be unnecessary - I recommend that you do not use multiple assemblies without a good reason.

The interfaces must be visible to the implementors. The implementation may be visible to consumers. If you want to separate the implementation from interface such that they can be deployed separately, then the interfaces should reside in their own assembly.
If you are disciplined enough to organize your code based on namespaces and have no special deployment requirements, the interfaces can reside in the same assembly as the implementation.

Interfaces to services (normally provide data and implemented as WCF) need to reside on a separate DLL and MVC will have a reference to.
So here is a typical (and basic) splitting of the classes and interfaces into projects (and assemblies):
Common
Entity (reference Common)
Service Interface (reference Common and Entity)
Service Implementation (reference all above)
Presentation (References all above but Implementation) and has WCF procies, view specific logic
MVC project (references all above but Implementation)

Related

Inversion of Control with .Net and assembly references

When using inversion of control in a .Net application, is it acceptable to add a reference to your data layer in your host application?
Say I have the following individual projects:
MyApp.Data (EF classes)
MyApp.Business (Service factory / repository)
MyApp.Services.MyWCFService (Host)
MyApp.Presentation.MVC (Host)
MyApp.Business.Tests (Host)
In this situation, I have historically used IoC between MyApp.Business and the host apps - creating interfaces for each service factory / repository, and using DI in the host application. Each application then has the choice to inject its own implementation of my business factories. I've never had an issue with this, as my host apps only ever rely on the business layer, and I never have to reference the MyApp.Data assembly (my MyApp.Business generally deals with all calls to the MyApp.Data assembly, and renders the results in to composite business objects).
What I'm trying to achieve with my latest project is to use IoC at every level - i.e. creating interfaces in MyApp.Data, so I can apply mocking and proper unit tests to MyApp.Business. It seems to me that the only way to achieve this is to create an assembly reference to both MyApp.Business and MyApp.Data in the host application, then use DI to inject both the MyApp.Data and MyApp.Business implementations.
This is contrary to everything I've been taught with conventional nTier applications, though I understand that it's DI that's doing all the work, and the reference is basically for resolution only. Am I right in assuming this is the right way to approach it? Is there a better way?
In short: Yes, it is acceptable to reference each and any part of your app from the main entry point of your application.
The concept is called Composition Root.

Dependecy Injection Library Agnostic Code using a Common Wrapper class?

Is anyone aware of a set of classes to abstract away the specific Dependency injection library (Spring, Castle, StructureMap, Ninject... etc.) ?
We all use a DI container to abstract away a specific implementation of our code, but we could also use the same interface / strategy pattern to write a generic interface based DI container using specific implementations such as Castle.Windsor, Unity... etc.
In general the basic pattern of "Getting and Object" from a container is pretty universal. For example:
IService service = IocContainer.Get<IService>();
Where IocContainer is a generic wrapper class around a specific library implementation such as Castle.Windsor, Unity... etc.
Of course in addition to writing specific implementations that you could 'plug-in' and of course, each implementation would have its own configuration file format.
Anyone have suggestions on existing well tested wrapper classes for DI containers?
The problem with all these wrappers and container abstractions is that they restrict you to the common subset of the functionallity that all the containers share. That's why you shouldn't do it. Instead use the container of your choice correctly:
Have just one "Get" in your application - in the composition root
Configure the container with conventions rather than usein a one by one service registration. This makes the configuration small.
Use factory interfaces wherever you have to create instances after the initial composition of your application and implement them as part of the container configuration (Some container do this implementation automatically for you)
With these simple rules your container is known in one place only - the composition root - which makes any abstraction of the container obsolete. That way you can use the full power of the container.

Improving Asp.net MVC Layers Arhitecture

I want to make a solid architecture for my MVC Project.
Currently, project has:
Database Objects (linqToSql)
ViewModels used for views
one Repository used for
- reading / editing / deleting database objects
- creating ViewModels for page
- other general functions
My initial structure is:
MvcApplication (MvcApplication.Common, MvcApplication.Domain, MvcApplication.Models)
- containing all the views, controllers, repositories
MvcApplication.Domain
- containing linqToSql data file
MvcApplication.Models (MvcApplication.Common, MvcApplication.Domain)
- containing ViewModels
MvcApplication.Common (MvcApplication.Domain)
- containing helper functions, and Enums
Can you advice me creating a better architecture for this project?
Which layer should i remove or not?
Should ViewModels be in the Domain Layer?
Viewmodels are the purvey of the implementation of the views. I do not feel as though viewmodels should be in the domain.
I would do the same thing with data access. I separate that layer, and only have the interfaces for persistence in the domain. I can then inject my data access at runtime. YMMV there though. Depends on the likelyhood of you swapping out the DAL later. Same with services. Interfaces for the services in the domain. Separate assembly for implementations.
DAL abstraction like this becomes VERY handy during testing, So i can run my unit tests against mocks, or a different storage mechanism completely.
I don't know about you but I hate having my logic tests tied to some database someplace. With multiple people running tests, how can i be sure of the integrity of the test DB, unless i do sql express?
I can't even tell you the number of times abstracting the services like that have saved my bacon. What, this services is slow because its all sync? Lets change the service implementation to shove a message in a queue. No changes to the application layers or anything.

MEF & separate Interface assembly leads to "Interface for every class"

I'm getting my feet wet with DI/IoC and MEF in particular.
I have a web application that has two types of parts (maybe more someday) defined by interfaces which need access to the whole environment. The application has a list with concrete implementations for each type, composed by MEF.
The environment consists of:
several repositories
current application request
render engine
navigation engine
plus some static utility classes
How can I put the Interface definitions in a seperate assembly and at the same time specify the environment injection?
Obviously, I can't just reference the main assembly because that needs to reference the contract assembly and I can't create a circular reference.
It seems that I need to create an interface for each of the environment classes, and their publicly available types and so on... There has to be a better way?!
Maybe I'm also missing the obvious bigger flaw here, if anyone could point it out for me?
If you want to decouple your abstractions from their implementations (always a worthy goal), you should define those abstractions in their own assembly.
From the implementation side, this is easy to deal with, becuase you need to reference the abstractions to implement them. There's no way around that whether you use MEF or not, so that's as it has always been:
[Import(typeof(IFoo))]
public class MyFoo : IFoo { }
However, as you say, this means that you can't reference your Composition Root from the abstraction library. However, that is as it should be, because the abstractions shouldn't worry about how they get composed.
In other words, you must implement the composition of the dependencies outside of the abstraction library. A good candidate for that is the executable itself, whereas you would keep all your concrete implementations in one or separate libraries.
The abstraction library will have no references, while both consumers and implementers would need to reference it, so a dependency graph might look like this:
Composition Root --> Abstractions <-- Implementations
Where the arrows denote a reference.

Taking my MVC to the next level: DI and Unit of Work

I have looked at simpler applications like Nerddinner and ContactManager as well as more complicated ones like Kigg. I understand the simpler ones and now I would like to understand the more complex ones.
Usually the simpler applications have repository classes and interfaces (as loosely coupled as they can get) on top of either LINQtoSQL or the Entity Framework. The repositories are called from the controllers to do the necessary data operations.
One common pattern I see when I examine more complicated applications like Kigg or Oxite is the introduction of (I am only scratching the surface here but I have to start somewhere):
IOC DI (in Kigg's case Unity)
Web Request Lifetime manager
Unit of Work
Here are my questions:
I understand that in order to truly have a loosely coupled application you have to use something like Unity. But it also seems like the moment you introduce Unity to the mix you also have to introduce a Web Request Lifetime Manager. Why is that? Why is it that sample applications like Nerddinner do not have a Web Request Lifetime Manager? What exactly does it do? Is it a Unity specific thing?
A second pattern I notice is the introduction of Unit of Work. Again, same question: Why does Nerddinner or ContactManager not use Unit of Work? Instead these applications use the repository classes on top of Linq2Sql or Entity Framework to do the data manipulation. No sign of any Unit of Work. What exactly is it and why should it be used?
Thanks
Below is a example of DI in Nerddiner at the DinnersController level:
public DinnersController()
: this(new DinnerRepository()) {
}
public DinnersController(IDinnerRepository repository) {
dinnerRepository = repository;
}
So am I right to assume that because of the first constructor the controller "owns" the DinnerRepository and it will therefore depend on the lifetime of the controller since it is declared there?
With Linq-to-SQL is used directly, your controller owns the reference to the data context. It's usually a private reference inside the controller, and so is created as part of its construction. There's no need in lifetime management, since it's in one place.
However, when you use IoC container, your data repository are created outside your controller. Since IoC container that creates it for you doesn't know how and how long you're going to use the created object, a lifetime strategy is introduced.
For example, data context (repository) is usually created at the beginning of the web request and destroyed at the end. However, for components that work with external web service, or some static mapper (e.g. logger) there's no need to create them each time. So you may want to say to create them once (i.e. singletone lifestyle).
All this happen because IoC container (like Unity) are designed to handle many situations, and they don't know your specific needs. For example, some applications use "conversation" transactions where NHibernate (or Entity Framework maybe) may last during several pages / web requests. IoC containers allow you to tweak objects lifetime to suit your needs. But as said this comes at price - since there's no single predefined strategy, you have to select one yourself.
Why NerdDinner and other applications do not use more advanced techniques is simply because they are intended to demonstrate MVC features, not advanced usages of some other libraries. I remember an article written to demonstrate one IoC container advanced functionality - this article broke some approved design patterns like separation of concerns - but this wasn't that important because design patterns were not the goal of the article. Same with simple MVC-demonstration-applications - they do not want you, the MVC newcomer, to be lost in IoC labyrinths.
And I would not recommend to look at Oxite as a design reference example:
http://codebetter.com/blogs/karlseguin/archive/2008/12/15/oxite-oh-dear-lord-why.aspx
http://ayende.com/Blog/archive/2008/12/19/oxite-open-exchangable-informative-troubled-engine.aspx
Most if not all of the DI containers touch the concept of life times, I believe. Depending on the scenario involved, you may want the container to always return the same instance of a registered component, while for another component, you may want it to always return a new instance. Most containers also allow you to specify that within a particular context, you want it to return the same instance, etc..
I don't know Unity very well (so far I have used Windsor and Autofac), but I suspect the web request lifetime manager to be an implementation of lifetime strategies where the same instance is provided by the container during the lifetime of a single web request. You will find similar strategies in containers like Windsor.
Finally, I suppose you are referring to Unit of Work. A Unit of Work is in essence a group of actions that you want to succeed or fail as one atomic business transaction. For a more formal description, look at Martin Fowler's definition. It is a concept that has gained more popularity in the context of Domain Driven Design. A unit of work keeps track of the changes you apply in such a transaction, and when the time is right, it commits these changes in one ACID transaction. In NHibernate e.g., the session supports the notion of unit of work and more specifically the change tracking, while in Linq2SQL it is the Context ...

Resources