hcp
hcp

Reputation: 3439

Convention based binding in ASP.NET 5 / MVC 6

It is possible to register dependencies manually:

services.AddTransient<IEmailService, EmailService>();
services.AddTransient<ISmsService, SmsService>();

When there are too much dependencies, it becomes difficult to register all dependencies manually.

What is the best way to implement a convention based binding in MVC 6 (beta 7)?

P.S. In previous projects I used Ninject with ninject.extensions.conventions. But I can't find a Ninject adapter for MVC 6.

Upvotes: 6

Views: 825

Answers (3)

hcp
hcp

Reputation: 3439

If it is still interesting for someone. This is my solution of the issue with Autofac. It is required Autofac and Autofac.Extensions.DependencyInjection NuGet packages.

// At Startup:

using Autofac;
using Autofac.Extensions.DependencyInjection;

// ...

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // Some middleware
    services.AddMvc();

    // Not-conventional "manual" bindings
    services.AddSingleton<IMySpecificService, SuperService>();

    var containerBuilder = new ContainerBuilder();
    containerBuilder.RegisterModule(new MyConventionModule());
    containerBuilder.Populate(services);
    var autofacContainer = containerBuilder.Build();

    return autofacContainer.Resolve<IServiceProvider>();
}

This is the convention module:

using Autofac;
using System.Reflection;
using Module = Autofac.Module;

// ...

public class MyConventionModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        var assemblies = new []
        {
            typeof(MyConventionModule).GetTypeInfo().Assembly,
            typeof(ISomeAssemblyMarker).GetTypeInfo().Assembly,
            typeof(ISomeOtherAssemblyMarker).GetTypeInfo().Assembly
        };

        builder.RegisterAssemblyTypes(assemblies)
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();
    }
}

Upvotes: 0

Steven
Steven

Reputation: 172606

No, there is no support for batch registration in the ASP.NET 5 built-in DI library. As a matter of fact, there are many features that are needed to build large SOLID applications, but are not included in the built-in DI library.

The included ASP.NET DI library is primarily meant to extend the ASP.NET system itself. For your application, you are best off using one of the mature DI libraries out there, and keep your configuration separate from the configuration that used to configure the ASP.NET system itself. This removes the need for an adapter.

Upvotes: 9

Fabio Salvalai
Fabio Salvalai

Reputation: 2509

An MVC 6 adapter exists, but seeing as ASP.net 5 is still in Release candidate, it isn't yet available on NuGet so you'll need to add the ASP.NET 5 "master" branch feed from MyGet to your Visual Studio NuGet package sources.

A walkthrough to do this is available here:

http://www.martinsteel.co.uk/blog/2015/using-ninject-with-mvc6/

Upvotes: 2

Related Questions