Using MEF , what would be the Extensible points in a web application? - asp.net-mvc

So, I've decided to use the Microsoft Extensibility Framework(MEF) with my new ASP.NET MVC web project. The project is a very typical employee management system, with 3 traditional layers :- a presentation layer (with views and controllers), a business layer (with business objects) and ofcourse, a data access layer. After some research, I read a lot, that MEF is supposed to help us implement the plug-in architecture.And this is where, I seem to get stuck. I'm not able to relate with this pluggable part. I'm pretty sure that, since MEF is the part of the core .NET framework, it is not limited to any specific kind of application, and is supposed to be useful in general. I just need to see my application structure in a new light, and that's where I need some helpful insights.
As I'm still trying to get started with MEF, my main question is; what would be the main extensible(pluggable) points in my application? What objects should one be typically composing using the MEF's compose method, and what would be the advantages of doing so using MEF instead of the traditional way?

MEF will not help you solve extensibility issues in the case you have described in the question, because it doesn't seem to have any. What MEF can bring to the table for this particular case is Dependency Injection. If you develop your application in a way that the presentation layer depends on business abstraction and the business layer depends on a data access abstraction rather than on concrete implementation, you will get a highly decoupled application that is easy to test, maintain and change without affecting unnecessary components. Here is one way to do this:
Lets say you have data access class that performs CRUD operations on employees:
[Export(typeof(IEmployeeRepository))]
public class EmployeeRepository : IEmployeeRepository
{
//Some logic here
}
As you can see the EmployeeRepository class implements IEmployeeRepository interface which adds the level of abstraction that is needed to develop a decoupled application. Now lets say that in the business layer you have a class that needs to call some method from the EmployeeRepository class. To be able to call a method of EmployeeRepository, you would need an instance of it. Without using MEF (or any other IoC framework, this would be a way to do it:
public class EmployeeManager
{
private EmployeeRepository _employeeRepository;
public EmployeeManager
{
_employeeRepository = new EmployeeRepository();
}
}
By using the above code sample, a hard dependency between the EmployeeManager and EmployeeRepository classes is created. This hard dependency is difficult to isolate when writing unit tests and causes any change of the EmployeeRepository class to directly affect the EmployeeManager class. By refactoring the code sample a little bit and putting MEF into the game, you'll get this:
[Export(typeof(IEmployeeManager))]
public class EmployeeManager : IEmployeeManager
{
private IEmployeeRepository _employeeRepository;
[ImportingConstructor]
public EmployeeManager(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
}
As you can see the EmployeeManager class now doesn't depend on the EmployeeRepository class, but it depends on IEmployeeRepository interface, in other words it depends on abstraction. And it doesn't create the instance of EmployeeRepository class by itself. That job is left to MEF. By now it should be clear that export and ImportingConstructor attributes are part of MEF and are used by it to discover parts and resolve dependencies at runtime. With the last code sample the classes are decoupled, easy to test and maintain and you can change the internal logic in EmployeeRepository class without making EmployeeManager class aware of it. Of course the contract between them, IEmployeeRepository have to be maintained.
The above said, can be used to decouple the presentation layer from the business layer also. Also the above said, can be implemented by using any other IoC framework, like Ninject, Autofac, StructureMap etc. The difference between these IoC frameworks and MEF is that if you use them, you'll need to configure at application start which instance gets created when some interface is encountered:
//something like this, in the case of Ninject
this.Bind<IEmployeeRepository>().To<EmployeeRepository>();
On the other hand, MEF has the ability to discover parts at runtime. On application start, you'll just need to inform it where to look for parts: Directory, Assembly, Type etc. The auto-wire capabilities of MEF (the ability to discover parts at runtime), make it more than a regular IoC framework. This ability makes MEF great for developing pluggable and extensible applications because you'll be able to add plugins while the application is running. MEF is able load them and let the application to use them.

Related

Dependency injection - trying to avoid using a service locator

Following the guidelines I read in:
https://www.devtrends.co.uk/blog/how-not-to-do-dependency-injection-the-static-or-singleton-container
I want to try and avoid using a service locator.
But on the other hand, I don't register all the types in the startup.cs file. I don't think this is right that all these internal types are referenced in the main startup.cs
I currently have a factory class that has a collection of builder classes.
Each builder class is in charge of creating a specific object.
I don't want to create all these builder classes in advance as I might not need to use them and creating them is a bit heavy.
I saw an example of how to achieve this in the link above. However the startup.cs class needs to know all these builders. I don't think this is appropriate, I'd rather have the factory class be the only one that is exposed to them. I was trying to understand if there is some kind of func/action method that I can inject from the startup.cs file into my factory class. This func/action will be in charge of creating/registering the builders and then I can activate this func/action within the class factory. I'd like this func/action to receive the interface/class/maybe name of the builder but using generics isn't working. I searched a lot and didn't find any solution so I assume this is not possible.
Seems I have 2 options:
1. Use service locator. This way only the factory class will know the builders. However if in the future, if I want to change the DI I need to "touch" the factory class (I'm contaminating the factory class). Wanted all the DI code to be located only in the startup.cs class.
2. Register the builders in the startup.cs but now the startup.cs is aware of the builders. This kinda couples the code, not really single role of responsibility
It would have been great to inject the factory class a func/action from the startup.cs that would do the registration but the factory class itself activates it.
Is this possible?
I want to try and avoid using a service locator
Great, because the Service Locator is an anti-patttern.
don't register all the types in the startup.cs file.
You should do your registrations in one single 'area' of your application: the start-up path. This area is commonly referred to as the Composition Root (the place where object graphs are composed).
I don't think this is right that all these internal types are referenced in the main startup.cs
No matter how you design it, the startup assembly is the most volatile part of the system and it always depends on all other assemblies in the application. Either directly or transitively (through another referenced assembly). The whole idea of Dependency Injection is to minimize the coupling between components and the way to do this is to centralize coupling by moving it to the Composition Root. By making types internal however, you are decentralizing object composition and that limits your flexability. For instance, it becomes harder to apply decorators or interceptors for those registered types and control them globally. Read this question and its two top voted answers for more information.
I don't register all the types
The concern of having a Composition Root that is too big is not a valid one. One could easily split out the Composition Root into multiple smaller functions or classes that all reside in the startup assembly. On top of that, if you read this, you'll understand that registering all types explicitly (a.k.a. "Explicit Register") is typically pointless. In that case you're probably better off in using DI without a Container (a.k.a. Pure DI). Composition Roots where all types are registered explicitly are not very maintainable. One of the areas a DI Container becomes powerful is through its batch-registration facilities. They use reflection to load and register a complete set of types in a few lines of code. The addition of new types won't cause your Composition Root to change giving you the highest amount of maintainability.
I don't want to create all these builder classes in advance as I might not need to use them and creating them is a bit heavy
Creation of instances should never be heavy. Your injection constructors should be simple and composing object graphs should be reliable. This makes building even the biggest object graphs extremely fast. Factories should be reduced to an absolute minimum.
TLDR;
Register or compose your object graphs solely in the Composition Root.
Refrain from using the Service Locator anti-pattern; Whole applications can (and should) be built purely with Constructor Injection.
Make injection constructors simple and prevent them from doing anything else than storing their incoming dependencies.
Refrain from using factories to compose services, they are not needed in most cases.

Dependency Injection - Passing dependencies all the way down

I have an MVC application with a typical architecture...
ASP.NET MVC Controller -> Person Service -> Person Repository -> Entity Framework DB Context
I am using Castle Windsor and I can see the benefit of using this along with a ControllerFactory to create controller with the right dependencies. Using this approach the Controller gets a Service injected, which in turn knows how to construct the right Repository, which in turn knows the correct DbContext to use.
The windsor config is something like this...
dicontainer = new WindsorContainer();
dicontainer.Register(Component.For<IPersonService>().ImplementedBy<PersonService>());
dicontainer.Register(
Component.For<IPersonRepository>().UsingFactoryMethod(
() => new PersonRepository(new HrContext("connectionString"))));
It this the right way to do it? I don't like the UsingFactoryMethod, but can't think of another way.
Also, what if the Repository needed a dependency (say ILogger) that was not needed by the service layer? Does this mean I have to pass the ILogger into the service layer and not use it. This seems like a poor design. I'd appreciate some pointers here. I have read loads of articles, but not found a concrete example to verify whether I am doing this right. Thanks.
I try to avoid using factory methods (as you mentioned you felt this smelled funny). To avoid this, you could create a database session object that creates a new DbContext. Then your repositories just need to get an instance of IDbSession and use its dbContext property. Then, you can also easily control the scope of the IDbSession object (don't use singleton because it's not thread safe).
I wanted to make that point so that I could make this more important point... Make your constructors take in only objects that are registered in the DI container (no options or configurations in constructors). Options and configurations should be read/writen in classes whose sole purposes it is to read/write those values. If all classes follow this model, then your DI registration becomes easy and classes can just add whatever dependencies they need in their constructors.
If you are trying to use a third party library that has options in constructors, wrap that class in your own class that has an easy to consume constructor and uses a configuration class to read the values needed to pass to the third party library. This design also introduces a layer of abstraction between your code and the third party library which can then be used to more easily swap (or stub) third party libraries when necessary.

Dependency Inject for models

I'm sure someone has asked this before, but I'm struggling to find where.
I'm using Ninject to remove dependencies from my controllers, along with a repository design pattern.
As I understand it, one of the benefits of this approach is that I can easily whip apart my repositories and domain entities and use another assembly should I so wish. Consequently I've kept my domain entities and repositories in external assemblies and can mock all my dependencies from interfaces.
It seems that while I can use interfaces to refer to my domain entities in most places I must use references to my concrete classes when it comes to model binding. I've read that this is to do with serialization which I understand, but is the only way to avoid referring to domain entities to create separate models?
Anything I can do with Custom Model Binding?
A bit of background: I'm an experienced ASP.net developer, but new to MVC.
View Models should be plain data containers with no logic and therefore shouldn't have any dependencies at all. Instead inject the repositories to your controller and have it assign the required data from the repository to the appropriate property of your view model.
The major advantage of using a dependency injection framework is IoC (Inversion of Control):
loosely coupling
more flexibility
easier testing
So what one usually does is to inject repositories through their interfaces like
public class MyController : Controller
{
private IPersonRepository personRepo;
public MyController(IPersonRepository personRepo)
{
this.personRepo = personRepo;
}
...
}
During testing this allows to easily inject my mock repository which returns exactly those values I want to test.
Injecting domain entities doesn't make that much sense as they are more tightly linked with the functionality in the specific class/controller and thus abstracting them further would just be an overhead rather than being a benefit. Instead, if you want to decouple your actual entity model from the controller you might take a look at the MVVM pattern, creating specialized "ViewModels".
Just think in terms of testability of your controller: "What would I want to mock out to unit test it?"
DB accesses -> the repository
External dependencies -> other BL classes, WS calls etc.
I wouldn't include domain entities here as they're normally just a data container.
Some more details would help. A bit of code perhaps?
To start with, you should avoid injecting dependencies into domain entities, but rather use domain services.
Some more info here.
Edit 001:
I think we should clarify our terminology.
There is the domain layer with all you domain entities, e.g. product, category etc.
Then there's the Data Layer with your repositories that hydrate your domain entities and then you have a Service Layer with you application services that talks to the data layer.
Finally you have a presentation layer with your views and controllers. The Controllers talk to you Aplication Service Layer. So a Product Controller talks to a Catalogue Service (e.g. GetProductBySku). The CatalogueService will have one or more repositories injected into its constructor (IProductRepository, ICategoryRepository etc.).
It's quite common in asp.net mvc to have ViewModels too. Put the ViewModels in your Application Service Layer.
So I'm not sure what you mean when you say "models" and "domain enntities" but I hope that clears up the terminology.

ASP.NET MVC: What goes where?

I am about to start developing a medium sized ASP.Net MVC application.
I am trying to get the design right. I intend to have the following layers:
UI layer (MVC)
Service Layer
Repository Layer
Data Access Layer
I will be using Unity as my IOC container and EF4.1 Code First for Data Access.
The app will be split into several assemblies. I have a problem deciding which assemblies I will need
and where to put the following:
Entities/Domain objects e.g. Customer, Invoice
DTOs e.g. CustomerDTO, InvoiceDTO
Service interfaces e.g. ICustomerService
Repository Interfaces e.g. ICustomerRepository
Services(Service interface implementation classes) e.g. CustomerService
Repositories (Repository Service implementation classes) e.g. CustomerRepository
ViewModels e.g. CustomerViewModel
Enums
My question is:
How do you usually split yours and why?
Edit: prompted by the #TheHurt's answer.
How would the references be between the assemblies, i.e. which assembly would be referencing which?
This is how I might tackle it:
App.UI assembly:
ViewModels go in Models area.
App.Repository assembly:
Abstract implementation of concrete repository.
ICustomerRepository
App.Repository.SQL:
Concrete implementation.
EFCF POCOs
App.Services assembly:
Abstract service.
ICustomerService
DTOs
App.Services.Implementation:
Concrete service.
CustomerService
App.Common:
Shared code.
Enums
There are a couple issues that I still struggle with. You lose the data annotations from EFCF when you cross the services boundary. So then you have to do server side validation or you have to keep your view models validation in sync with the repository entities. It feels that the more layered things are, the more DRY is violated. I suppose that is par for the course though when your view models don't map to your entities directly. You could have your view models be your DTOs and toss them into the Common assembly, but that seems to couple things too tightly if you have the need to be super flexible with your services.
EDIT
If you are wanting to integrate WCF into the mix you would probably want to create data contracts that are very close to the MVC view model (or use the contracts as the view model). You probably wouldn't expose that to the world as the service would be specific to that implementation of your MVC site, spin up another service for public consumption. If you are doing a WCF service you probably want to have all of your business logic in the service, the controllers would just handle navigation logic.
Side note, I try to stay away from the "metal" as much as possible, while developing a design that will allow me to separate the code into various layers in the future. If I cannot clearly explain the various system layers to my manager with one sheet of paper, the design is more than likely too complex. Everything for the most part will look pretty in Visio if it is designed well.
As far as how things reference each other: UI would ref the Serivce (or service implementation, which may not be needed. Just keep it all in the same place.). Service refs the Repository. The repository implementation refs nothing, since it is loaded by IOC. Everything refs Common.

S#arp Architecture: How to arrange Application Services

With S#arp Architecture, my understanding is that domain logic (aka business logic) that operates on more than one type of entity is best handled by the Application Services layer.
So the classes in Application Services will need access to the Repositories. Presumably then you inject the Repositories in via the constructors. Because there is one class of repository per entity type, any fairly realistic task is going to need access to several repositories. So you might have an Application Services class looking like this:
public class DogTasks
{
public DogTasks(IRepository<Dog> dogRepository,
IRepository<Trick> trickRepository,
IRepository<DogTrick> dogTrickRepository,
IRepository<Lesson> lessonRepository)
{
// etc
}
public void TeachDogNewTrickAtALesson(int dogID, string trickName, int lessonID)
{
// etc
}
// other methods, etc
}
This Tasks class can then be injected into the relevant Controller.
So far, I think I get it. But I am perturbed by the following:
When I need a new Application Services method that uses a combination of repositories that I don't have yet, I have to choose between changing the constructor for one of my existing classes to accept the new repositories, or starting a new class altogether. Adding arguments to constructors upsets a lot of the unit tests, but proliferating new classes doesn't seem good either.
When Controllers need to do simple Repository operations (like a get) it makes sense to inject the repositories into the Controllers as well as the Application Services classes. But then I get the same 'changing constructor arguments' issue. The other alternative seems to be to only let the Application Services layer play with the Repositories, but then you get a lot of boilerplate code added to the Application Services to do very simple things.
These sorts of things make me think I might be doing it wrong. So how should a good Application Services layer be organised?
e.g. Do you have lots of classes that just do one task each? Or do you clump related tasks together along entity lines? How do you deal with tasks that need a lot of repositories? Does needing a lot of repositories for a task mean its time to go back to the drawing board?
First, I'd like to counter your assumption that each entity needs its own repository. Per, Eric Evans "Domain Driven Design"
Repositories give access to selected aggregate roots. Repositories are prohibited from the interior of an aggregate.
Given your example, a dog has a set of tricks that it has learned. When you want to add a new trick to the dog, you'd do something like this:
var dog = dogRepository.Get(dogId);
dog.Tricks.Add(newTrick);
dogRepository.SaveOrUpdate(dog);
When I need a new Application Services method that uses a combination of repositories that I don't have yet,
I'm not sure what you mean by this. But I think if you stick to using repositories for aggregate roots, you're not going to run into such messy code.
The other alternative seems to be to
only let the Application Services
layer play with the Repositories, but
then you get a lot of boilerplate code
added to the Application Services to
do very simple things.
Controllers orchestrate. Think of controllers as a part of the UI, they move you from page to page. I will admit that for simple things, it seems simpler to just inject a repository into the controller, but when your project grows the separation will help a lot, especially if you end up having another application hook into your Tasks layer. Keep repositories out of controllers.
e.g. Do you have lots of classes that
just do one task each? Or do you clump
related tasks together along entity
lines? How do you deal with tasks that
need a lot of repositories? Does
needing a lot of repositories for a
task mean its time to go back to the
drawing board?
Again, I think this goes back to defining aggregate roots. Having 4-5 repositories in a task isn't that big of a deal. I usually organize my tasks by what the application is trying to do, with the idea that if the UI changes to, say, an external JSON request, you just need to call the right task.
Hope this answers your question. Feel free to post this on the Sharp mailing list, you might get a better response there.
Edit based on comments:
Check out Who Can Help Me (https://github.com/sharparchitecture/Who-Can-Help-Me) for an example of how to use the ApplicationServices/Tasks layer. They have a fairly small domain model so each entity has its own task.
I think you're confusing terminology a bit, or perhaps I'm being unclear. The idea behind an ApplicationServices layer is to further abstract the UI from the domain layer. Repositories are domain layer entities, and knowledge of them should not be in the controller. If you end up swapping out ORM or even moving to a document-based storage system, you'll see why this abstraction makes it really convenient, you just need to make sure your ApplicationServices contracts are working and don't have to muck about in the controllers.
But, don't confuse the need for ApplicationServices as a way of future proofing. It simply allows for further decoupling between your layers and decoupling is nearly always a good thing.
Again, for a project you're working on solo, all this might seem a bit of overkill. When you're working with other developers, all this abstraction is really, really nice. You can have a team working on upstream domain issues, and a team working on the presentation layer, and have a nice separation of concerns.
Have you heard about Abstract Factory pattern? It solves this problem in a nice way:
public interface IDalFactory
{
// One way
IRepository<Trick> TrickRepository { get; }
IRepository<Dog> DogRepository { get; }
...
// Other way
IRepository<T> GetRepository<T>();
}
public DogTasks
{
public DogTasks(IDalFactory dalFactory)
{
...
}
}
It is up to you how do you implement IDalFacotry. I usually using lazy initialization of repositories. Once repository is created it is internally stored and reused. One factory instance is created per http request.
The cons is that you don't have control over factories exposed to your application service. But that are your choices. Adding new repositories to constructor or using factory.

Resources