Skip to main content

Posts

Showing posts with the label Dependency Injection

ASP.NET Core - Use factory based middleware with scoped services

Yesterday I talked about a problem we encountered when trying to inject a scoped service into ASP.NET Core middleware. The middleware used was convention based middleware, one of the ways to construct middleware in ASP.NET Core. With convention based middleware there isn’t a base class or interface to implement. The only rules your middleware class needs to apply to are: It has a public constructor with a parameter of type RequestDelegate . It contains a public method named Invoke or InvokeAsync . This method must: Return a Task . Accept a first parameter of type HttpContext . Convention based middleware is registered with a singleton lifetime, so you can only constructor injection for the dependencies with a singleton lifetime. For transient and scoped dependencies you need to add extra parameters to the InvokeAsync() method: There is a log of magic going on when using convention based middleware and it shouldn’t be a surprise that pe...

ASP.NET Core–Cannot resolve from root provider because it requires scoped service

A colleague contacted me with the following problem; when running his ASP.NET Core application it failed with the following error message: Cannot resolve IApiLoggingService from root provider because it requires scoped service NHibernate.IInterceptor In this post I walk you through the different steps we took to investigate the issue and explain how we solved it. But before I dive into the problem itself I first want to give some background info on dependency injection in ASP.NET Core and service lifetimes. Dependency injection and service lifetimes ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. Registration of a dependency is done in the built-in service container, IServiceProvider . Services are typically registered at the app's start-up and appended to an IServiceCollection . Once all services are added, you use BuildServiceProvider to...

Microsoft.Extensions.DependencyInjection–Register a type with all its interfaces

After using other DI containers like Microsoft Unity, StructureMap and Autofac, I'm now using the built-in Microsoft.Extensions.DependencyInjection DI container most of the time.  The default DI container lacks some more advanced features that these other containers have, but for most use cases it is sufficient. Most of the time when registering a type as a service, you want to register it with the interface it implements: To simplify this I created an extension method AsImplementedInterfaces that register a type with all its interfaces: To use this method, you call any of the Add methods on the IServiceProvider and call the AsImplementedInterfaces method afterwards: Feel free to use it in your own projects... Remark: If you are looking for some other convenience methods that can help you when using the default DI container, check out Scrutor .

Microsoft.Extensions.DependencyInjection - Check if a service is registered in the DI container

After using other DI containers like Microsoft Unity, StructureMap and Autofac, I'm now using the built-in Microsoft.Extensions.DependencyInjection DI container most of the time.  The default DI container lacks some more advanced features that these other containers have, but for most use cases it is sufficient. This week I was looking at a way to check if a specific service was registered in the DI container without resolving and constructing the service instance. Turns out that this feature was introduced in .NET 6 through the IServiceProviderIsService interface (what’s in a name). This interface provides a single method that you can invoke to check whether a given service type is registered in the DI container. To use it, you can resolve the IServiceProviderIsService service itself from the container and call the IsService method: Nice!

.NET 8–Keyed/Named Services

A feature that a lot of IoC container libraries support but that was missing in the default DI container provided by Microsoft is the support for Keyed or Named Services. This feature allows you to register the same type multiple times using different names, allowing you to resolve a specific instance based on the circumstances. Although there is some controversy if supporting this feature is a good idea or not, it certainly can be handy. To support this feature a new interface IKeyedServiceProvider got introduced in .NET 8 providing 2 new methods on our ServiceProvider instance: object? GetKeyedService(Type serviceType, object? serviceKey); object GetRequiredKeyedService(Type serviceType, object? serviceKey); To use it, we need to register our service using one of the new extension methods: Resolving the service can be done either through the FromKeyedServices attribute: or by injecting the IKeyedServiceProvider interface and calling the GetRequiredKeyedServic...

Applying the decorator pattern in .NET Core using Castle.DynamicProxy

In this post I want to explain what the decorator pattern is, why it is useful and how you can implement it in a generic way using Castle.DynamicProxy. What is the Decorator pattern? Before we dive into the technical details, let us start with a recap about what the decorator pattern actually is: Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors. There are a lot of use cases where the decorator pattern can help, in this blog post I focus on one of them; using a decorator to handle cross cutting concerns(caching, error handling, logging, …) without polluting your original object. I’ll show you an example where I introduce caching at the repository interface level. How to integrate the decorator pattern in a generic way? You don’t need a special library or anything to implement the decorator pattern in C#. However I would like to write it in a gener...

InvalidOperationException: Cannot resolve from root provider because it requires scoped service

A colleague contacted me with a specific error she got. The strange thing was that the error never appeared during local development but only after deploying the application to our Development environment. Let's first have a look at the error message: The error happens during the bootstrapping of the application. For me it was immediately clear what the problem was but if you don’t spot the root cause, no worries. I’ll show you the related code, maybe that helps. First here is the specific Serilog enricher: And here is the bootstrapping code: The problem occurs when we resolve the ILogger singleton instance. When we do this a transient enricher is used that injects a scoped IUserFactory. As there is no scope available at that moment, this leads to the error above. To fix it, we have to change the lifetime of our IUserFactory to transient: > Than the question remains: Why this error doesn’t happen during local development? The answer is Scope Validation ...

.NET Core Dependency Injection–Check if a service is already registered

It is way too hot today to write a long post, so I focus on a small but useful new feature in .NET 6. As I mentioned before in most of my projects I'm using Autofac as the Inversion of Control container of my choice. One of the features that Autofac has to offer is the IsRegistered method which allows you to check if a specific type is already registered in the IoC container. Starting from .NET 6, you can do a similar thing with the Microsoft DI container using the IServiceProviderIsService interface: You first need to resolve the interface from the container and then you can call the IsService() method to see if the service can be resolved through the container or not: That’s it! Time to cool down(literally)…

XUnit - Log ILogger messages to the test output

By default logging inside XUnit can be done through the ITestOutputHelper . But this is only useful in situations where you are inside in your test code and have direct access to this interface. Most of the logging in your application however, is typically happening inside the application logic itself(through the ILogger<T> provided by .NET). So if we want to capture this information, we need a way to create a bridge between the two. Luckily we don't have to create such a solution ourselves, but can use one of the available open source projects that solve exactly this issue. I decided to give MartinCostello.Logging.XUnit a try. Installation To install it, just add is as a Nuget package to your XUnit test project: dotnet add package MartinCostello.Logging.XUnit Usage To use, it you should register the adapter as your ILogger in Microsoft DI container: Remark: I first had a look at Divergic.Logging.Xunit but it wasn't so easy to integrate it as p...

Using Autofac in .NET 6 Minimal API’s

Before .NET 6 Minimal API’s you had 2 places where you had to apply some changes to replace the built-in IoC container with Autofac. First in your Program.cs file: And second in your Startup.cs file: But what should you do when using .NET 6 Minimal API’s ? In that case your Startup.cs file is gone. You still need to apply the same 2 steps but this time directly on the Host property of the WebApplicationBuilder : Remark: I assume that the process is quite similar for other 3th party IoC containers.

ASP.NET Core–Typed HttpClient

One of the ways that you can inject an HttpClient instance in your ASP.NET Core application is through ‘Typed clients’ . It is my preferred way as it takes maximal benefit from dependency injection, avoid the magic strings that ‘Named clients’ need and allows you to encapsulate the client configuration in one place. A typical example of a named client is this: This is possible thanks to following registration: Most examples of the typed client you find out there are using a concrete class(like in the example above) but I wanted to use an interface. Here was my first (naive) attempt: The result of the code above was that an HttpClient instance was injected but it wasn’t using the configuration values I specified in the Startup.cs. A second attempt was to specify the named client on the interface but this caused the same problem. The correct solution is the following:

XUnit–Dependency Injection

To use the standard IoC container inside your Xunit tests, I would recommend to use a separate fixture. Inside this fixture you can add all dependencies to the ServiceCollection and build the ServiceProvider: Now you can use the IoC container inside your tests by injecting the fixture inside the constructor:

NHibernate –Dependency Injection enabled IInterceptor

Yesterday I showed the AuditInterceptor we are using in one of my applications. Maybe you noticed that we were using dependency injection: Important to notice is that we are injecting a scoped dependency that contains the current user id(through the IUserFactory). The trick to get this working is to set the interceptor when the session is created. Therefore we register our IInterceptor implementation in the IoC container(Autofac in our situation): Then when we construct a new session instance we’ll get the IInterceptor from the container and link it to the session:

ASP.NET Core–Use dynamic proxy with standard dependency injection - Async

Yesterday I blogged about using Castle.DynamicProxy to generate a proxy class and use AOP techniques for caching. The code I showed worked for synchronous method calls but fails when you want to proxy async method calls. Let’s see how we can get this working for async… Here is the async version of our repository: We need an extra NuGet package: dotnet add Castle.Core.AsyncInterceptor Now we have to change our interceptor to call a second async interceptor: Our extension method that triggers the proxy creation remains the same: Our registration code should be extended to register the async interceptor as well:

ASP.NET Core–Use dynamic proxy with standard dependency injection

You don’t need to use a 3th party IoC container to use AOP(Aspect Oriented Programming) and the proxy pattern in ASP.NET Core. We’ll combine the power of Castle.DynamicProxy and the standard DI to make this possible. Castle's dynamic proxies allows you to create proxies of abstract classes, interfaces and classes (only for virtual methods/properties). Let’s create an example that caches the output of a repository call. Here is the example repository that we want to proxy: Now we first need to create an interceptor that intercepts the method calls and caches the response: Let’s move on to the DI registration. We first need to create an extension method that triggers the proxy creation: Almost there, as a last step we need to register everything:

Using a scoped service inside a HostedService

When trying to resolve a scoped dependency inside a HostedService, the runtime returned the following error message: System.InvalidOperationException: Cannot consume scoped service ‘IScoped’ from singleton ‘Microsoft.Extensions.Hosting.IHostedService’. The problem is that the IHostedService is a singleton and is created outside a dependency injection scope. Trying to inject any scoped service(e.g.  an EF Core DbContext) will result in the error message above. To solve this problem you have to create a dependency injection scope using the IServiceScopeFactory. Within this scope you can use the scoped services:

Microsoft Orleans–Integrate with your favorite IoC container

As mentioned in a previous post , it is not that hard to start using dependency injection with Orleans. But what if you don’t want to use the built-in IoC container? To switch the IoC container instance you can call the UseServiceProviderFactory() method exposed by the SiloHostBuilder. Here is an example that uses StructureMap:

ASP.NET Core Scope Validation

While preparing a training about .NET Core I stumbled over a feature I was unaware it existed in ASP.NET Core: Scope Validation. One of the nice things inside ASP.NET Core is that it has built-in support for Dependency Injection . Service lifetime When registering your dependencies you have 3 service lifetimes to choose from: Transient: Transient lifetime services are created each time they're requested. This lifetime works best for lightweight, stateless services. Scoped: Scoped lifetime services are created once per request. Singleton: Singleton lifetime services are created the first time they're requested (or when ConfigureServices is run and an instance is specified with the service registration). Every subsequent request uses the same instance. Simple so far. The problem is that you can shoot yourself in the foot when you start combining multiple lifetimes in the same object tree.  For example when using a scoped service in a middleware, and you...

ASP.NET Core–Injecting dependencies in an MVC ActionFilter

ASP.NET Core out-of-the-box supports dependency injection on the action filter level. You have to use constructor injection to inject your dependencies in the actionfilter: However now it is no longer possible to simply add the action filter as an attribute on top of your controller or action method. This is because attributes must have their constructor parameters supplied where they are applied. Instead you have to use one of the following attributes: TypeFilterAttribute ServiceFilterAttribute The key difference is that TypeFilterAttribute will find and load the dependencies through DI, and inject them into your action filter. The ServiceFilterAttribute on the other hand attempts to find the filter from the service collection. This means that you have to register your actionfilter first:  

If you have too many dependencies it’s time for something else

I’m a big fan of the Inversion of Control(IoC) pattern and how Dependency Injection(DI) frameworks can help you implement this pattern.  IoC was really a gamechanger to me and had a lot of impact on the way I build and architect my applications. Note: As I’m doing more and more functional programming, the need to use a DI framework is going away, but that’s something to discuss in another blog post Unfortunately something I see a lot in applications that use a DI framework is something I call “dependencies diarrhoea”. Let’s have a look at an example ASP.NET MVC controller to illustrate the problem: So what’s the problem here? Without even looking at the full implementation, it should be clear that this class is violating the ‘Single Responsibility Principle’ and is doing too much in one class. This not only makes it harder to reason about this class, but also makes it a lot harder to test. There is no fun in mocking out lots of dependencies just to test a small piece ...