Protocol Based Binding in ASP.NET 5 / MVC 6

You can register dependencies manually:

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

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

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

PS In previous projects, I used Ninject with ninject.extensions.conventions . But I can not find the Ninject adapter for MVC 6.

+5
source share
3 answers

If it is still interesting to someone. This is my solution to the problem with Autofac . Autofac and Autofac.Extensions.DependencyInjection NuGet packages are required.

 // 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 a conditional 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(); } } 
0
source

No, there is no support for batch registration in the built-in DI library in ASP.NET 5. In fact, there are many functions needed to create large SOLID applications, but are not included in the built-in DI library.

The included ASP.NET DI library is primarily intended to extend the ASP.NET system itself. For your application, it is best for you to use one of the mature DI libraries, and save your configuration separately from the configuration that was used to configure the ASP.NET system itself. This eliminates the need for an adapter.

+8
source

The MVC 6 adapter exists, but after seeing that ASP.NET 5 is still in the Release candidate, it is not yet available in NuGet, so you need to add the ASP.NET 5 master feed from MyGet to your Visual Studio NuGet package sources.

A step-by-step guide for this is available here:

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

+2
source

Source: https://habr.com/ru/post/1232021/


All Articles