Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply decorators with ASP.NET Core Dependency Injection

Tags:

On an ASP.NET MVC 5 application I have the following StructureMap configuration:

cfg.For(typeof(IRequestHandler<,>)).DecorateAllWith(typeof(MediatorPipeline<,>)); 

Does anyone know how to do this configuration with ASP.NET Core IOC?

like image 521
Miguel Moura Avatar asked Apr 12 '16 11:04

Miguel Moura


People also ask

What are decorators in .NET core?

Decorator design pattern falls under Structural Pattern of Gang of Four (GOF) Design Patterns in . Net. Decorator pattern is used to add new functionality to an existing object without changing its structure. Hence Decorator pattern provides an alternative way to inheritance for modifying the behavior of an object.

What is IServiceCollection in .NET core?

AddScoped(IServiceCollection, Type, Type) Adds a scoped service of the type specified in serviceType with an implementation of the type specified in implementationType to the specified IServiceCollection.

Can we use dependency injection in .NET framework?

NET supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. Dependency injection in . NET is a built-in part of the framework, along with configuration, logging, and the options pattern.

What is Scrutor?

Scrutor is an open source library that adds assembly scanning capabilities to the ASP.Net Core DI container.


2 Answers

The out of the box IoC container doesn't support decorate pattern or auto discovery, which is "by design" as far as I know.

The idea is to provide a basic IoC structure that works out of the box or where other IoC containers can be plugged in to extend the default functionality.

So if you need any advanced features (support for a specific constructor, auto-registering of all types which implement an interface or inject decorators and interceptors) you have to either write it yourself or use an IoC container which offers this functionality.

like image 159
Tseng Avatar answered Sep 18 '22 13:09

Tseng


Use Scrutor. Just install the nuget package and then do the following.

services.AddSingleton<IGreeter, Greeter>(); services.Decorate<IGreeter, GreeterLogger>(); services.Decorate<IGreeter, GreeterExceptionHandler>(); 

The order is important. In the above, GreeterLogger decorates Greeter. And GreeterExceptionHandler decorates GreeterLogger.

If you need more info, take a look at this and this.

like image 45
VivekDev Avatar answered Sep 20 '22 13:09

VivekDev