Implementing DI & IoC Pattern in MVC 4 with MEF 2 Attributeless using Conventions with RegistrationBuilder in .NET 4.5

  • Update, downloadable sample using MEF with System.ComponentModel.Composition.Web.Mvc Preview 5 – 05/31/2013
  • Update, downloadable sample using Unity 3.0 for MVC 4 – 06/03/2013

From my previous article Generically Implementing the Unit of Work & Repository Pattern with Entity Framework in MVC & Simplifying Entity Graphs – Part 1, we covered how to properly setup your project and implement the Unit Of Work and Repository patterns. In this article, we’ll take our solution the next logical progression, which is getting DI (Dependency Injection) & IoC (Inverse of Control) patterns implemented.

DI & IoC will bring many advantages to our solution. a few of them are as follows.

  1. Programming against abstractions and away from our concrete implementations.
  2. Complementing the previous item, allowing us replace or select concrete implementations during run-time.
  3. Giving us an easy way to mock-up certain implementations for quick unit tests.

Now there are many other debatable benefits for DI & IoC, and I’ll let you make you form your own opinions on this topic, however for the purposes of this post, let’s jump into implementation. We will start off, where we left off in our solution, from our previous post.

First we will need to go ahead and get MEF (Managed Extensibility Framework) wired up, we can get a jump start to this by using our MVC MEF library from my blog post found here.

Note: There are two methods MEF will register exports and imports, one by attributes, which most of know about, the second, is by conventions. I’ve searched high and low on how to get MEF working with MVC using MEF Registrations and have absolutely zero luck, so with that being said, more reason to setup our solution using MEF Registrations (convention based) vs. the Attribute approach

With the Mv4.Mef project added and referenced in our Web project, let’s go ahead and wire up the some code in our Web startup. Now, instead of polluting our Global.asax.cs Application_Start() method with all our MEF Registrations and Conventions, let’s follow the MVC pattern, by adding a MefConfig.cs class under the App_Start folder with the rest of the application start-up code resides.

5-17-2013 7-37-59 PM

Web.App_Start.MefConfig.cs


    public static class MefConfig
    {
        public static void RegisterMef()
        {
            // Set up all the Mef conventions for our web assembly
            var registrationBuilder = new RegistrationBuilder();

            registrationBuilder.ForTypesDerivedFrom<Controller>()
                .SetCreationPolicy(CreationPolicy.NonShared).Export();

            registrationBuilder.ForTypesDerivedFrom<ApiController>()
                .SetCreationPolicy(CreationPolicy.NonShared).Export();

            registrationBuilder
                .ForTypesMatching(t =>
                    t.FullName.StartsWith(
                        Assembly
                            .GetExecutingAssembly()
                            .GetName().Name + ".Parts."))
                .SetCreationPolicy(CreationPolicy.NonShared)
                .ExportInterfaces(x => x.IsPublic);

            var aggregateCatalog = new AggregateCatalog();

            aggregateCatalog.Catalogs.Add(
                new AssemblyCatalog(Assembly.GetExecutingAssembly(), registrationBuilder));

            // Set up all the Mef conventions for our repository assembly
            registrationBuilder = new RegistrationBuilder();

            registrationBuilder.ForTypesDerivedFrom<IUnitOfWork>().Export<IUnitOfWork>();

            aggregateCatalog.Catalogs.Add(
                new AssemblyCatalog(typeof(IUnitOfWork).Assembly, registrationBuilder));

            // Set up all the Mef conventions for our data assembly
            registrationBuilder = new RegistrationBuilder();

            registrationBuilder.ForTypesDerivedFrom<IDbContext>().Export<IDbContext>();

            aggregateCatalog.Catalogs.Add(
                new AssemblyCatalog(typeof(IDbContext).Assembly, registrationBuilder));

            // Add all our catalogs with Mef conventions to our container
            MefMvcConfig.RegisterMef(new CompositionContainer(aggregateCatalog));
        }
    }

Now let’s invoke our MEF configuration from the Global.asax.cs Application_Start() method.

Web.Global.asax.cs


namespace Web
{
    public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            MefConfig.RegisterMef();
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
}

So we everything from line 5 to 51 is simply setting up all the import and export mappings from all of our projects or assemblies, I’ll go over some of the conventions we are setting up with the MEF’s RegistrationBuilder.


            registrationBuilder.ForTypesDerivedFrom<Controller>()
                .SetCreationPolicy(CreationPolicy.NonShared).Export();

Her we are saying go ahead and export everything that inherits or is derived from Controller, which means go ahead and add all of our controllers to the Composition Container.


            registrationBuilder.ForTypesDerivedFrom<ApiController>()
                .SetCreationPolicy(CreationPolicy.NonShared).Export();

Here (same principles as the previous item) we are saying go ahead and add all of our Web Api Controllers to the container.


            registrationBuilder
                .ForTypesMatching(t =>
                    t.FullName.StartsWith(
                        Assembly
                            .GetExecutingAssembly()
                            .GetName().Name + ".Parts."))
                .SetCreationPolicy(CreationPolicy.NonShared)
                .ExportInterfaces(x => x.IsPublic);

In this block of code, we are saying go ahead and export everything that implements a public interface as the interface it’s implementing that in the Parts folder in our web project as exampled here http://msdn.microsoft.com/en-us/library/hh708870.aspx.


            registrationBuilder
                .ForTypesDerivedFrom<IUnitOfWork>().Export<IUnitOfWork>();

This is pretty straight forward export anything that is derived from IUnitOfWork as IUnitOfWork. Great, hopefully this sheds some light on how we can setup some conventions for export and import mapping for our Composition Container.

Now let’s revisit to our CustomerController we were working on previously.

Before:


    public class CustomerController : Controller
    {
        public ActionResult Index(int? page)
        {
            var pageNumber = page ?? 1;
            const int pageSize = 20;

            var unitOfWork = new UnitOfWork();

            int totalCustomerCount;

            var customers =
                unitOfWork.Repository<Customer>()
                    .Query()
                    .Include(i => i.CustomerDemographics)
                    .OrderBy(q => q
                        .OrderBy(c => c.ContactName)
                        .ThenBy(c => c.CompanyName))
                    .Filter(q => q.ContactName != null)
                    .GetPage(pageNumber, pageSize, out totalCustomerCount);

            ViewBag.Customers = new StaticPagedList<Customer>(
                customers, pageNumber, pageSize, totalCustomerCount);

            unitOfWork.Save();

            return View();
        }
    }

Now, lets inject all our dependencies that the CustomerController has using one of MEF’s supported Import methods, Constructor Injection.

After:


    public class CustomerController : Controller
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ICustomerService _customerService;

        public CustomerController(
            IUnitOfWork unitOfWork, 
            ICustomerService customerService)
        {
            _unitOfWork = unitOfWork;
            _customerService = customerService;
        }

        public IUnitOfWork UnitOfWork { get; set; }

        public ActionResult Index(int? page)
        {
            var pageNumber = page ?? 1;
            const int pageSize = 20;

            int totalCustomerCount;

            var customers =
                _unitOfWork.Repository<Customer>()
                    .Query()
                    .Include(i => i.CustomerDemographics)
                    .OrderBy(q => q
                        .OrderBy(c => c.ContactName)
                        .ThenBy(c => c.CompanyName))
                    .Filter(q => q.ContactName != null)
                    .GetPage(pageNumber, pageSize, out totalCustomerCount);

            ViewBag.Customers = new StaticPagedList<Customer>(
                customers, pageNumber, pageSize, totalCustomerCount);

            return View();
        }
    }

Let’s debug and make sure that the IUnitOfWork is getting injected with Constructor Injection from MEF by putting int two breakpoints, first one in the MefMvcControllerFactory so we can take a peek at the Catalog in our Composition Container and the second one in the CustomerController itself.

5-17-2013 5-33-56 PM

Now here we see that all of our previously wired up MEF conventions are valid, we see all of our Controllers, Services, UnitOfWork and NorthwindContext in our CompositionContainer, great! Now for a sanity check, let’s take a look at our CustomerController to ensure that we are actually getting injected now that we validated our container.

5-17-2013 5-43-22 PM

Now let’s just take a quick look at our UnitOfWork and CustomerService objects and notice how there are not attributes decorated anywhere and that they are indeed being added to our CompositionContainer by the conventions we setup earlier with the RegistrationBuilder.

Repostiory.UnitOfWork


namespace Repository
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly IDbContext _context;

        private bool _disposed;
        private Hashtable _repositories;

        public UnitOfWork(IDbContext context)
        {
            _context = context;
            InstanceId = Guid.NewGuid();
        }

        public Guid InstanceId { get; set; }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        public virtual void Dispose(bool disposing)
        {
            if (!_disposed)
                if (disposing)
                    _context.Dispose();

            _disposed = true;
        }

        public IRepository<T> Repository<T>() where T : class
        {
            if (_repositories == null)
                _repositories = new Hashtable();

            var type = typeof (T).Name;

            if (!_repositories.ContainsKey(type))
            {
                var repositoryType = typeof (Repository<>);

                var repositoryInstance = 
                    Activator.CreateInstance(repositoryType
                            .MakeGenericType(typeof (T)), _context);
                
                _repositories.Add(type, repositoryInstance);
            }

            return (IRepository<T>) _repositories[type];
        }
    }
}

Web.Parts.CustomerService


namespace Web.Parts
{
    public class CustomerService : ICustomerService
    {
        private readonly IUnitOfWork _unitOfWork;

        public CustomerService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public void UpdateWithAddressValidation(Customer customer)
        {
                // Example stubbed method, for same UnitOfWork 
                //instance injetction test with page request scoped
        }
    }
}

Awesome, our CustomerController is being handled and instantiated by MEF, therefore it is also handling all the Dependency Injection in the CustomerController e.g. IUnitOfWork and the ICustomerService.

5-17-2013 5-43-22 PM

Now, one very important note, notice that I’ve added a property the UnitOfWork named InstanceId of type Guid. I’ve deliberately drilled down the UnitOfWork.InstanceId in both the UnitOfWork and CustomerService objects in the debug mode screenshot, so that we can see that they are both indeed the same instance. This is very important when using MEF with MVC, that by default, the Scope of the items life cycle are per page request, and will be disposed of after the request has completed. For scenarios where we deliberately want an instance to live for the entire life cycle of the application we can set CreationPolicy for that export to be shared.

Happy Coding..! :)

Download sample applications:

Self managed life-cycle using HTTP scoped IUnitOfWork, IDbContext using HttpContext.Current.Items with MEF

https://skydrive.live.com/redir?resid=949A1C97C2A17906!5107&authkey=!AIfx5T8CZ5LlxAs

HTTP scoped using System.ComponentModel.Composition.Web.Mvc Preview 5, which I have upgraded to target .NET 4.5 using MEF

https://skydrive.live.com/redir?resid=949A1C97C2A17906!5108&authkey=!ACJE75BhOdiDSwI

Same solution from post, using the new Unity 3 for MVC 4 instead of MEF
Used the NuGet command install-package Unity.Mvc4 from the Package Manager Console for this one.

https://skydrive.live.com/redir?resid=949A1C97C2A17906!5152&authkey=!APcotdtSZzXZtzo

About these ads

70 thoughts on “Implementing DI & IoC Pattern in MVC 4 with MEF 2 Attributeless using Conventions with RegistrationBuilder in .NET 4.5

  1. hi le,

    you did a really good job, to explain a newbe this quite big topic of IoC, DI and the layering and seperation of the project.

    But i still have some open questions, what you didnt dealed with.
    following that Best Practice http://www.codeproject.com/Articles/667522/ASP-NET-MVC-Best-Practices i have a seperate ViewModel for each View, what makes sense to me. (for achieving that, i highly recommend the http://automapper.org/ ). Your Repo gives me back the POCO(s). Now to my question:
    What is the best place for the conversion from the Entities to the VMs? Extension methods into the repo project? or better into an service into the service project?

    I would really be thankful for a hint.

    Greetz, Toni

    • Do them via a Service in a Service Project for portability, converting your domain models into view models really doesn’t fall under the concern of the Repository which is where CRUD lives. Also if you ever create any other presentation layers e.g. mobile, you can use the re-use the service for View Models in other apps. The other apps wouldn’t be using your Repository layer directly, the would most like get to the data via REST or some other web service.

  2. Hello le,

    I really like your blog posts and I read ‘em all. ;)

    I am using the architecture of this post for one of my projects, but one thing I don’t like is the fact that in the web project I had to add a reference to the Data Project to have the IDbContext interface in Web.App_Start.MefConfig.cs as shown above for composing issues. Because I want to be able to switch (customerspecific) implementations of IDbContext I put this interface in a seperate project and therefor I only have to reference the interface project. But if I wouldn’t have to switch the implementations, how would you compose (or organise the projects) without using the IDbContext interface?

    Marcus

  3. Once Again great blog!
    Can you please reference to how would I go about unit testing any of the controllers? How can I mock UnitOfWork’s repository using any mock framework (such as Moq).
    An example will be even better!
    Thanks a lot!

  4. Hi Buddy, I do love your post about the EF + UoW + Repository pattern. The thing is I love Ninject as the IoC/Di. Is that possible for you to provide a quick example for Ninject?

    Thanks much!

    • Thx for the positive feedback HorseKing, due to time constraints I wont’ be able wire one up using Ninject. For the most part, UoW and Repo implementation seen here should be fairly easy to wire up with up with any DI & IoC framework out there, especially with the Ninject Nuget Packages that are available for MVC 4. Just setup your bindings for the IUnitOfWork and DbContext and you should be good. The Ninject MVC WebActivator for their bootstrapper will do do pretty much all the heavy lifting in terms of getting the MVC runtime to resolve instances with their container.

  5. Thanks again Le, really helpful information. I’m going to be adding Unity 3 to my Business Logic aka Service Layer. In your parting thoughts at the end, you state to use Unity.MVC4.

    The Business Logic aka Service Layer (just before the Web API facade) is going to be tying to the components: Data (with Context & Configuration), Mode (Entities), Validation, Repositories (with UoW).

    Please correct me, wouldn’t I use the vanilla Unitity 3 product and not the Unity.MVC4 at the Business Logic/Service Layer (since it’s not MVC4 related)?

    Then, the WebAPI would consume the Business Logic/Service Layer and serve this up to the MVC project for the controllers? This means that the Web API layer would just be a pass through for the HTTP request and the MVC would take these Web API RPCs and pass the data to and from the Views? At the MVC layer, it would need DI (Unity 3) in order to understand the entity structures being returned from the Web API. No UoW, no Repos, at the Web API or MVC layers, just RPC request/response of RPC structures?

    • Yes, you would use the vanilla Entlib Unity 3 Nuget Packages that are MVC 4 ready e.g. these will wire up the MVC runtime for DI & IoC for all controller types e.g. Controller, Web API, EntitySetController (for OData configured Controllers), etc.

    • Yes, Web API or any other controllers for that matter, would be the consumers of your UoW and Repos, and Services (e.g. IProductService). All your controllers will be injected with them.

      Yes, your Web API are the entry point for your Http requests, in most cases you do not want business logic or data access code here, data access implementation needs to reside in your Repo project/layer and your business logic needs to reside in your Service (business) layer/project. If your Services layer needs data access you need to inject them with your UoW/Repos.

      Not sure I understand your last question: “At the MVC layer, it would need DI (Unity 3) in order to understand the entity structures being returned from the Web API. No UoW, no Repos, at the Web API or MVC layers, just RPC request/response of RPC structures?”

      The MVC layer consist of Views, Controllers (all types, Controller, WebApi, EntitySet, etc.). I’m assuming here your using MVC layer analogous with Views? If so, then no your Views should usually not be injected with any UoW or Repos, however that’s not to say that they can’t be injected with other useful View services e.g. http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvcdependencyinjection_topic3.aspx. For your Views to understand the Models that are being returned from your Controllers, just strongly type the View to a ViewModel (which could contain the Model/Entity/Dto) or to the Model, if your doing Razor. If your doing something like Kendo UI, then just create your ViewModels on the client side (JavaScript), and you want to use their MVVM framework. You can read up on the blog post series on Kendo UI that I’ve sent you for implementation details.

    • Hi Le,

      Observation:

      In the solution that you posted that uses Unity.Mvc4,

      * There is a reference to Unity.Mvc4

      * The *default* Bootstrapper.cs file that gets added when one adds the Unity.Mvc4 via NuGet are in the Repository project. There is no registration of any components

      * There then seems to be no utilization of the Unity IoC framework anywhere in the Repository project.

      * IoC is implemented in the Repository project via Constructors in the various patters: e.g., Repository(IDbContext context) and UnitOfWork(IDbContext context).

      Question (by the way, there’s no way to post with a picture on here is there?):

      * Why do we need Unity.Mvc4 in the Repository project?

      * Isn’t the Repository project utilizing Class Constructors for IoC?

      * Won’t *only* the Controllers in the MVC project use Unity.Mvc4 implementation of IoC to inject the implementations of the UoW/Repos/Services (located in the Repository project)?

      Thanks again!

    • Please see my answers inline:

      I used an older project for the sample, please update accordingly.

      * There is a reference to Unity.Mvc4
      Remove if not needed.

      * The *default* Bootstrapper.cs file that gets added when one adds the Unity.Mvc4 via NuGet are in the Repository project. There is no registration of any components
      Uninstall and install the official EntLib Nuget Pacakges (screenshot I posted).

      * There then seems to be no utilization of the Unity IoC framework anywhere in the Repository project.
      Correct, if you find a need to inject anything here you can, however we are injecting our Controllers with IUnitOfWork and IRepository, so didn’t need DI & IoC in the Repo layer, however in my latest solution, I do have DI & IoC for some other duties.

      * IoC is implemented in the Repository project via Constructors in the various patters: e.g., Repository(IDbContext context) and UnitOfWork(IDbContext context).
      No, these are not injected, I’m actually passing those instances in when instantiating Repos, see the UnitOfWork class, method: Repository via Reflection. However in my currently implementation I am using DI & IoC for this.

      Question (by the way, there’s no way to post with a picture on here is there?):
      Not sure…

      * Why do we need Unity.Mvc4 in the Repository project?
      You can remove.

      * Isn’t the Repository project utilizing Class Constructors for IoC?
      No, however it can, I’m doing this currently, just not in the sample download.

    • Le, thank you for the reply.

      A little more context:

      I have a Service layer (that will act as an interface UI and Data Access layers) that has a direct reference to Data (Which has Context, Mappings), Entities (POCOs), and Repository (which has UoW) projects.

      This service layer will not need IoC containers for resolving implementations, instead they’ll get their UoW via Constructor Injection like so:

      public interface ITenantService
      {
      IEnumerable GetTenants();
      void GetTenantById(string id);
      void CreateTenant(Sales_Tenant tenant);
      void UpdateTenant(Sales_Tenant teant);
      void DeleteTenant(string id);

      void AddTenantWithAddressValidation(Sales_Tenant tenant);
      void AddOrUpdateTenant(Sales_Tenant tenant);
      }
      public class TenantService : ITenantService
      {
      private readonly IUnitOfWork _unitOfWork;

      public TenantService(IUnitOfWork unitOfWork)
      {
      _unitOfWork = unitOfWork;
      }

      #region CRUD
      public IEnumerable GetTenants()
      {
      // add page number and page size to this
      var tenants = _unitOfWork.Repository()
      .Query().Get();

      return tenants;
      }
      public void GetTenantById(string id)
      {
      _unitOfWork.Repository().FindById(id);
      }
      public void CreateTenant(Sales_Tenant tenant)
      {
      tenant.State = Model.ObjectState.Added;
      _unitOfWork.Repository().Insert(tenant);
      _unitOfWork.Save();
      }
      public void UpdateTenant(Sales_Tenant tenant)
      {
      tenant.State = Model.ObjectState.Modified;
      _unitOfWork.Repository().Update(tenant);
      _unitOfWork.Save();
      }

      public void DeleteTenant(string id)
      {
      var tenant = _unitOfWork.Repository().FindById(id);
      tenant.State = Model.ObjectState.Deleted;
      _unitOfWork.Repository().Delete(tenant);
      _unitOfWork.Save();
      }

      #endregion

      #region RPC
      public void AddTenantWithAddressValidation(Sales_Tenant tenant)
      {
      // Might need to adjust this as tenantdetails and the address table has some of the detailed information.
      _unitOfWork.Repository().AddTenantWithAddressValidation(tenant);
      }
      public void AddOrUpdateTenant(Sales_Tenant tenant)
      {
      var itemExists = _unitOfWork.Repository().FindById(tenant.BusinessEntityId);

      if (itemExists != null)
      {
      tenant.State = Model.ObjectState.Modified;
      _unitOfWork.Repository().Update(tenant);

      }
      else
      {
      tenant.State = Model.ObjectState.Added;
      _unitOfWork.Repository().Insert(tenant);
      }

      _unitOfWork.Save();
      }
      #endregion
      }

      Side note, I’ll have a thin WebAPI layer that sits between the Service Layer and the MVC Web Application.

      The MVC Application will use IoC using Unity and dependency resolver in the bootstrapper/glabal.asx.

    • Le,

      “…however we are injecting our Controllers with IUnitOfWork and IRepository, so didn’t need DI & IoC in the Repo layer, **however in my latest solution, I do have DI & IoC for some other duties.**”

      “No, these are not injected, I’m actually passing those instances in when instantiating Repos, see the UnitOfWork class, method: Repository via Reflection. **However in my currently implementation I am using DI & IoC for this.**”

      “Isn’t the Repository project utilizing Class Constructors for IoC?
      No, however it can, **I’m doing this currently, just not in the sample download.**”

      Do you mind providing an example of of this so I can get a better understanding of how this is properly constructed?

  6. HI Lee,

    Can I use the same concept for adding another project and try to load the plugin dynamically in the main web like a shell with dynamically loaded plugins with sub projects..

    Thanks
    Chinnu

    • Hi Chinnu and Behnam,

      Great questions and concerns in regards to pluggable modules for MVC e.g. having these modules reside in their own actual projects so that you don’t end up with with a gigantic monolithic solution.

      First off, if you are trying to accomplish this exact use case/architecture, I would highly recommend you do this with what MVC offers out of the box with no IoC and DI framework needed (e.g. MEF, Unity, Ninject, etc..). Meaning MVC already supports this today as it is. You can read up on how to implement this here http://blog.longle.net/2012/03/29/building-a-composite-mvc3-application-with-pluggable-areas/. Being that I’ve implemented MVC pluggable architectures both ways, I would recommend you go with this recommendation (which is the non IoC & DI approach).

      With this being said, let me know if you guys would still like to see pluggable architecture with MVC using Unity 3.0. I have the solution, I don’t imagine it would take look to do a quick write up on MVC modulization with Unity. However, knowing that I don’t recommend this as a best practice, there will be some heart burn if I were to publish it. :)

    • Hi Le,
      As far as I know with MEF you have to have a default empty constructor and Interception not possible. So you won’t be able to apply AOP in the application. So I wonder how you can use other libraries like enterprise library in an application with MEF. Perhaps I’m not aware of all features and possibilities of MEF 2, and that’s why I still think Unity is a better architectural choice for building large pluggable enterprise applications.

      Behnam

    • MEF vs. Unity is a fairly debatable topic. As far as standards go in the enterprise, Unity has been my choice. One of the downloads for the sample application is actually in Unity 3.0, and all blog posts following this post all use Unity 3.0 for IoC & DI.

      Although, Unity seems like the overall choice, MEF definitively has it’s strengths over Unity when it comes to plug and play (modules) due to it’s discovery nature specifically with assemblies and vice versa Unity definitely shines in areas as you mentioned, method interception, DI & IoC, etc. Coming from a WPF, Silverlight and Visual Studio Plugin development background, MEF is a pretty powerful framework, more on the pluggable side than it’s DI & IoC features, which some have also debated if MEF is even a true DI & IoC library.

    • Last but not least, we the sudden stop of MEF deep integration with web e.g. MVC, I’m somewhat unsure of MEF’s future or road map. The plan was this http://msdn.microsoft.com/en-us/library/hh708870.aspx, slated to be bundeld in with .NET 4.5 release, however last I heard on this effort was this https://mef.codeplex.com/discussions/361444. With this being said, it was just another reason why we struggled deciding if MEF had a place in our overall Enterprise strategy, since we have some significant app density in the web space.

    • Le,
      Due to previous incidents and company restrictions I decided not to have Twitter account anymore.
      Besides that, I am too busy with designing a new architecture for a large enterprise application. That was actually the reason I came to your blog ;-)

  7. Hi,
    I got the controller type, But now I’m not able to open the database, I changed the connection string

    Cannot open database “TestMefDB” requested by the login. The login failed.
    Login failed for user ‘sa’.

    Can you help me..

    Regards
    Chinnu

    • Hi Chinnu,

      Not sure why and what this error means, my best guess is because your credentials are set up right in your connection string or either the database doesn’t have the right permissions granted for the credentials in your connection string.

    • HI Lee,

      Manually I created the DB “TestMefDB”, then it is giving me the error
      ” System.Data.SqlClient.SqlException: Invalid object name ‘dbo.Customers’.”

      Regards
      Chinnu

    • Hi Lee,

      Its working fine . The problem was
      // Table & Column Mappings
      this.ToTable(“Customers”);
      I changed the name to “Customer” and works perfectlly

      Thank you

  8. Hi Lee,

    I downloaded the link MVC 4 & DI, IoC with MEF 2 Attributeless Conventions .NET 4.5 – Part 2. But I’m getting the error “Value cannot be null. Parameter name: type” in

    var export = _compositionContainer.GetExports(controllerType, null, null).SingleOrDefault();
    here the controllerType is null.

    Can you please tell me where I’m wrong.

    Regards
    CHinnu

    • Hi Chinnu,

      Because the MEF roadmap is a bit unclear with supporting MVC, I would highly recommend you download the third example download which is the same solution using Unity 3. Let me know if you still need help with MEF.

  9. Pingback: Modern Web Application Layered High Level Architecture with SPA, MVC, Web API, EF, Kendo UI | Long Le's Blog

  10. Pingback: Building an Extensible Fluent Validation Framework using Generic Funcs and Wiring it up to MVC 4 | Long Le's Blog

  11. Awesome post ! It has really helped me a lot, thanks !

    I wanted to get your opinion on validation of your entities. You have very basic validation in your configuration/mappings classes using IsRequired(), HasMaxLength() and so on, but how would you handle more complex validation that can’t really go into a custom attribute ?

    You could easily attribute your entity class with IValidateableObject but you then have validation in two separate locations (in the configuration class and in your entity class) and I don’t like that, it makes maintenance and debugging a bit of a pain.

    Would you remove the validation from the configuration class and use IValidateableObject combined with data annotations in your entity class or would you suggest some other way?

    • hi jf,thanks for the positive feedback, and I’m actually trying to wrap up a blog post that addresses your specific question, in terms of how to handle custom validation in the enterprise. I’ll Tweet (@LeLong37) once this is posted.

    • fj, Building an Extensible Fluent Validation Framework using Generic Funcs and Wiring it up to MVC 4 has been posted.

    • I saw that, thanks Le. I’ll have a good read of that post when I get home from work.

      I have another question about your sample here.

      In an enterprise application, you may have hundreds of entities. Is lumping them all into the same data project and context a wise idea? Are there performance hits by having it all together.

    • fj, that’s a pretty loaded topic, for example if you have a fairly large database that covers the entire enterprise, you may want to separate context that is specific to it’s domain. For example, let’s say you have a table Sales.History table, and you realize that has nothing to do with Employees.Insurance table, well in this case you may implement the Bounded Context Pattern from DDD. Again, this is a loaded topic and really depends on many considerations from the database, how your repository is organized, the business itself and how the data is related.

    • Hi Le, thanks for taking the time to answer. We’ve been discussing various options at work and as you have hinted, using bounded contexts seems to be the way to go in large applications like ours (300+ database tables). By breaking our application into ‘functional areas’ and having a context for each we think it will be more manageable. Pluralsight has a reasonable course titled ‘Entity Framework in the Enterprise’ discussing this approach, which we’ve used as a starting point.

      Thanks again, fj

    • You bet, I think your approach for Bounded Context sounds reasonable given the amount of tables you have. If you haven’t already you may want to go ahead and organize your database with the usage of SQL Schemas (the schema names or areas should match up fairly closely with the Bounded Contexts you are going to setup), good luck…!

  12. System.ComponentModel.Composition.Web.Mvc problem :

    When encounter @Html.Action(“List”) in a View , I get this error :

    System.InvalidOperationException: A single instance of controller ‘Zakos.Controllers.ItemsController’ cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request.

    There are many posts about it when googling ,I noob with MEF & don’t really know how to modify your solution , if you can update a fix for it , would be great , thanks again!

  13. Pingback: Generically Implementing the Unit of Work & Repository Pattern with Entity Framework in MVC & Simplifying Entity Graphs – Part 1 | Long Le's Blog

    • I don’t see why we would need Unity anymore with MEF 2, since we now have RegistrationBuilder to help bind our interfaces with our concrete implementations, I’m probably missing something here, anyhow let me know.

      Unity

      
      var container = new UnityContainer();
      container.RegisterType<IFoo,Foo>();
      container.RegisterType<IBar,Bar>();
      
      
      

      MEF

      
                  registrationBuilder.ForType<Foo>().Export<IFoo>();
                  registrationBuilder.ForType<Bar>().Export<IBar>();
      
      
    • there is no particularly reason , just more familiar with it + had some ideas to use it , but its probably good to know MEF too :)

    • well now its there , I see there is also UnitOfWorkPerPageRequest , very cool !

      Question : Why I need ICustomerService on CustomController and not just use IUnitOfWork for every controller? Is there other reason then demonstrate the MEF magic?

      Thanks again! very helpfull

    • Typically, you have all your CRUD related things in your UnitOfWork.Repository, however if your are doing heavy business logic/rules, you want that code to live in your Services layer (business layer) e.g. CustomerService, OrderService, ProductService, etc., these will typically reside in a Services Project e.g. Northwind.Service. I’ll cover that in the next blog post.

      Last but not least, I’m going to upload another solution that uses System.ComponentModel.Composition.Web.Mvc, which will essentially default the life cycle of everything in the CompositionContainer to the HTTP Request Scope, meaning the life-cycle of an instance will be defaulted to the lifetime of an HttpRequest unless you explicitly set it to CreationPolicy.Shared which will set the life-cycle of that particular type to the Application life-cycle. This way we don’t have to write a custom UnitOfWorkRequestPerPage to scope it’s life-cycle to an HttpRequest.

    • ok i’ll ask different variation of HOW , how can I check its HTTP Request Scope?

    • Very impressive Le!

      I just discovered your blog, and wow, you have a lot of great, insightful , and in-depth coverage of useful and current patterns/practices/technology. All backed up with code example.

      Will you be generating a post on service architecture & best practices around this area, sometime soon?

      Suggested topic headline:
      EF6, UoW/Repo CRUD w Repo extensions and Validation checks, (maybe OData), consumed by Service Layer + Business Logic (Domain?) with a Web API facade consumed by MVC with DI sprinkled throughout (Unity for IoC/MEF for drop in UI components) & Tests, and maybe Kendo UI on top?

      Thanks again for everything, and let us know if/how we can contribute!

    • Follow up,

      Do you have anything to share in the way of SaaS and Multi-tenant architecture (both DB and Application)? Keeping in mind you’ve introduced me to MEF, would this technology help with different tenants sharing the service-to-db layers, yet having their own UI layer (different URL and configurable with metadata or the like)? I was thinking of using Kendo UI for the front end, and the MVC wrapper it provides. But I need a flexible way to (possibly) modify the UI of each tenant — and MEF seems like it would allow me to plug a different UI component for each tenant. Am I way off in this line of thinking?

      Thanks –

    • Please use Unity 3.0, setup a convention based registration to scan you assemblies, and then scan for specific Interfaces you’ve implemented e.g. IMyPlugin to inject these plugins into your application. Seems like MEF has stop development for DI & IoC for MVC, and at the moment MEF’s future in the web space is unclear. At the moment Unity offers much more support and features for MVC than MEF.

    • Thanks Le,

      I will take your advice and use Unity 3.0. This post is for MEF, but your sky drive project files has a Unity 3 example. I’ll open this up for study and try to apply this to my framework.

    • Aaron,

      Thanks for the positive feedback. To get the architecture you are referring to, which can been seen here:

      Modern Web Application Layered High Level Architecture with SPA, MVC, Web API, EF, Kendo UI, OData

      http://blog.longle.net/2013/06/13/modern-web-application-layered-high-level-architecture-with-spa-mvc-web-api-ef/

      You can follow this blog series:

      Part 1 – MVC 4, Kendo UI, SPA with Layout, View, Router & MVVM
      http://blog.longle.net/2013/06/17/mvc-4-kendo-ui-spa-with-layout-router-mvvm/
      Part 2 – MVC 4, Web API, OData, EF, Kendo UI, Grid, Datasource (CRUD) with MVVM
      http://blog.longle.net/2013/06/18/mvc-4-web-api-odata-entity-framework-kendo-ui-grid-datasource-with-mvvm/
      Part 3 – MVC 4, Web API, OData, EF, Kendo UI, Binding a Form to Datasource (CRUD) with MVVM
      http://blog.longle.net/2013/06/19/mvc-4-web-api-odata-ef-kendo-ui-binding-a-form-to-datasource-crud-with-mvvm-part/

      Which would cover everything you asked about.

      For the validation with OData, you can see how to wire this up here:

      Building an Extensible Fluent Validation Framework using Generic Funcs and Wiring it up to MVC 4 with ModelValidatorProvider and ModelValidator

      http://blog.longle.net/2013/06/03/building-an-extensible-fluent-validation-framework-using-generic-funcs-and-wiring-it-up-to-mvc-4/

      After using this extensible Validation Framework, you can just simply call Model.IsValid in your OData WebApi controller, as you normally would in MVC.

      if (ModelState.IsValid)
      {
      }

      Btw, I highly recommend that you use Unity 3.0 vs. MEF.

    • Wow, such a expansive body of work!

      I’m currently working on the DB and Application architecture for a Azure SaaS.

      I referenced your Generic UoW and Repo designs — thanks.

      ***
      But I’m really having trouble finding a solid example of a Business Logic layer to tie together [general Repo queries], [Repo requesting data from another Repo in the same Context], and even [two Contexts requesting data from one another].
      ***

      I’ll look into your other projects to see if you have a Business Layer or the equivalent tying everything together.

      Even so, I’m not building out the business logic yet, so I have time — right now I’m going to review your Unity 3 project to wire the backend to WebAPI/MVC.

      Again, amazing work!

    • Aron,

      Solid example of Bus Logic with Repo Queries.

      1. Create a Service Project to address separation of concerns, e.g. Repo vs. Services.
      2. Your service class should look like this:

      fictitious example:

      
      namespace Northwind.Service
      {
          public interface IProductService
          {
              bool ValidateProductWorkflow(Product product);
          }
      
          public class ProductService : IProductService
          {
              private readonly IUnitOfWork _unitOfWork;
      
              public ProductService(IUnitOfWork unitOfWork)
              {
                  _unitOfWork = unitOfWork;
              }
      
              public bool ValidateProductWorkflow(Product product)
              {
                  var supplier = _unitOfWork
                      .Repository<Supplier>()
                      .Query()
                      .Filter(
                          t => t.SupplierID == product.SupplierID                         
                              && t.Products.Any(u => u.ProductID == product.ProductID)
                       )
                      .Get()
                      .Single();
      
                  return supplier == null;
              }
          }
      }
      
      

      The Repo is extensible, see how to do this here:

      http://blog.longle.net/2013/05/11/genericizing-the-unit-of-work-pattern-repository-pattern-with-entity-framework-in-mvc/#Extensibility

      Now where ever you are trying to consume this new service e.g. IProductService like in a Web Api controller, simply inject it.

      
              private readonly IUnitOfWork _unitOfWork;
              private readonly IProductService _productService;
      
              public ProductController(IUnitOfWork unitOfWork, IProductService productService)
              {
                  _unitOfWork = unitOfWork;
                  _productService = productService;
              }
      
      
      
  14. Cool ,for the last few days I searched articles about upgrading my project into DDD model and MEF/Unity ( btw , why MEF ? ) , and this is the jackpot – last fresh materials! :)
    I didn’t dive in yet , do you use / plan to , to store the lifetime of a unitOfWOrk
    into HttpContext ? which from reading is the suggested way for using unitOfWork

    Ref : http://weblogs.asp.net/shijuvarghese/archive/2010/05/07/dependency-injection-in-asp-net-mvc-nerddinner-app-using-unity-2-0.aspx

    Thanks , looking forward for more

    • Yes, I’ll update this blog post with MEF lifecycle management, btw, you can follow me on Twitter @LeLong37 if you want, for updates.

  15. Hi Long

    It appears that your download link is pointing to a not MEFified solution.
    Anyways, I have replicated exactly what you showed in the steps in the hope of getting web api MEFified, but I’m keep getting a “type does not have a default constructor error”. It seems MEF has got trouble to instantiate the controller in question. I stepped through and the container did fail to produce a controller instance, it gives back a null value instead.

    The dependency chain is like this: webapi controller –> repository –> DbContext. I tried to debug it and I can see all 3 parts are in the catelog. I see no reason why it can’t instantiate the controller, I’ve even checked the connection string setting in the webconfig file. The error message is somewhat helpless so I’m wondering if you could shed some light here?

    Btw, I’m using vs2010, a little ancient. Thanks.

    • Hi Binjie,

      This is the correct download https://skydrive.live.com/redir?resid=949A1C97C2A17906!5105&authkey=!AAS4uIVQmb5tIPE, excuse the name of the actual zip file, could be misleading. For starters, please make sure you can download and run the sample solution. As for your issues, you have to drill down to the composed parts (in your case the Controller) and look at the export and import profile for each of them and make sure you have an export that matches all the imports for a given Controller or object that is being injected by MEF, so in short you will need to make sure that the CompositionContainer has all of the items that are being injected as well as their dependencies. If there isn’t a matching export for one of its imports, than the MVC runtime will handle the initializing the Controller which defaults the parameterless constructor, because this is the only constructor the MVC runtime knows how to handle. Let me know if you have any other issues.

Please Leave a Reply or Tweet me @LeLong37...!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s