Meta

Month: April 2016

Today I presented on Elasticsearch at the MVP Western Europe Community Open Day 2016, in Rome. Apart from some problems with the magnifier tool, and taking much longer than I should , I think it went relatively well!

If you are interested, you can find the PowerPoint deck and the sample steps in my One Drive here.

Back after a few weeks. For those who don’t know, this series of posts is dedicated to bringing some of the futures that existed in Entity Framework but were dropped in Core. You can find the first post here and the second here.

This time, an often forgotten feature that didn’t made it to Core: entity validation. Most of the posts that talk about what’s new usually forget about validation having been left out.

The key here is the Validator class: it knows how to perform all these validations, including finding all validation attributes in the class and in each property. In case of an error, we just throw a ValidationException with the error message, and the saving is aborted.

Introduction

There are quite a few good posts out there on Inversion of Control (IoC) and Dependency Injection (DI) in the ASP.NET Core world, but I felt there was still something to be said, hence this post! Mind you, this is going to be a long one! I once wrote another post on the history of dependency resolution in .NET, you may want to have a look at it. Always keep in mind that this is based on the latest bits, and may still change when it gets to the final version.

Services Registration

At bootstrap, ASP.NET Core will either call the ConfigureServices method, or one with a name following the convention Configure<environment>Services, where <environment> comes from the Hosting:Environment environment variable, and you can also set it in Visual Studio:

It is commonly set to “Development”, “Production”, “Staging”, etc. Keep in mind that if the environment-specific method exists (e.g., ConfigureDevelopmentServices), then the generic one (ConfigureServices) is not called.

The Configure*Services method is passed an instance of IServiceCollection, which is where we get to store our service registrations, so that they can be used by ASP.NET Core further along the pipeline. A service registration needs three things:

A key type, normally an interface or an abstract base class;

A concrete implementation of the key type;

A lifetime.

The lifetime determines how many times the concrete implementation is going to be built. The ASP.NET Core service provider implementation knows about three different lifetimes:

Scoped: an instance is created the first time it is requested during the same HTTP request, and during that request, this same instance is always returned;

Singleton: an instance is created the first time it is requested, and this same instance is always returned in all subsequent calls;

Transient: a new instance is always created, whenever it is requested.

A registration is an instance of the ServiceDescriptor class that is added to the IServiceCollection instance:

There are several extension methods that make this registration even easier.

What if you want to have custom processing when a service is returned? Simple:

services.AddTransient<IMyService>(sp =>

{

var something = sp.GetService(typeof(ISomething)) as ISomething;

var other = new OtherService();

//do something with it

returnnew MyService(other);

});

Keep in mind that the concrete service must either implement or inherit from the key service. Also, for the Scoped lifetime, if the concrete class implements IDisposable, the service provider will honor it and call Dispose at the end of the HTTP request.

After Configure*Services, ASP.NET Core calls Configure, also in the Startup class. This is where the core initialization occurs, like, adding all middleware, such as the MVC one, that makes the application works the way we expect it. The Configure method can either have no parameters or it can receive one or more parameters with types that match the registered services. For example, we will always have IApplicationBuilder, IHostingEnvironment, ILoggerFactory, so we can add them as parameters together with our own:

publicvoid Configure(

IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory,

IMyService service)

{

//do something with the services

}

It gives us a good chance to initialize them before the actual fun begins. If we want, we can also pass it just an instance of the dependency resolution service, represented by the IServiceProvider interface, which has been around since the early days of .NET. The ASP.NET Core service provider implements this interface, so having it here just means: “get me the service provider implementation so that I can retrieve services from it”:

Services

Each concrete service class itself can be dependency-injected: by default, it should be a concrete class and have a public parameter-less constructor; if, however, we want to inject dependencies into it, which also need to be registered in the service provider, we can have a constructor that takes these dependencies:

publicclass MyService : IMyService

{

public MyService(IServiceProvider serviceProvider)

{

//get something from the service provider

}

}

Notice the usage of IServiceProvider again. Another option is to have the constructor contain more concrete dependencies:

publicclass MyService : IMyService

{

public MyService(ILoggerFactory loggerFactory)

{

//do something with the logger factory

}

}

You can pass any number of parameters, of any type that is registered in the service provider, normally in one of the Configure*Services methods. If the specified service type is not registered, you get an exception at runtime.

Controllers

An MVC controller can have dependencies injected through its constructor, like I’ve shown for services:

publicclass HomeController : Controller

{

public HomeController(IMyService service)

{

//do something with the service

}

}

The same pattern applies: we can either declare a parameter as IServiceProvider or as a more specific type. It doesn’t matter if our controller inherits from Controller or is a POCO controller.

There was another dependency injection possibility with MVC controllers, which consisted in decorating public properties with a [FromServices] attribute: if a registration exists that matched the property’s type, it would be injected into the property just after the controller is constructed:

publicclass HomeController

{

[FromServices]

public IService Service { get; set; }

}

This is no longer possible, and the functionality was removed in DNX RC2, although it will still work in RC1. Forget about it.

By default, controller classes themselves do not come from the dependency resolution mechanism. You can achieve that, if, in Configure*Services, you call AddControllersAsServices, passing it either a Type or an Assembly collection:

Each time MVC tries to build an HomeController, it will instead get the same SingletonHomeController. Note that I am not saying that you should do this, but I think you get the idea!

Filters

Filters in MVC allow you to intercept action method calls, results and exceptions, and do stuff before, after of instead of the real actions. You have global filters and attribute filters: global filters apply always, and attribute filters only apply in the scope where they are declared – a controller’s class or an action method. Filters themselves can have dependencies injected into them.

In order to declare global filters, you use one of the overloads of the AddMvc method, normally in the Configure*Services method, and registering the filter as a service:

services.AddMvc(mvc => mvc.Filters.AddService(typeof(GlobalFilter)));

MVC will try to resolve the filter type, if necessary, injecting it any dependencies, in the usual way:

publicclass GlobalFilter : IActionFilter

{

public GlobalFilter(IMyService service)

{

//do something with the service

}

publicvoid OnActionExecuted(ActionExecutedContext context)

{

}

publicvoid OnActionExecuting(ActionExecutingContext context)

{

}

}

The other option for filters is attributes, but attributes require a public parameter-less constructor. The MVC team came up with an alternative for that, in the form of the ServiceFilterAttribute and TypeFilterAttribute attributes. Both receive a Type and the difference is that the first will try to resolve that type from the services registration and the last one will just instantiate it. Let’s see an example:

[ServiceFilter(typeof(GlobalFilter))]

publicclass HomeController : Controller

{

[TypeFilter(typeof(SomeFilter))]

public IActionResult Index()

{

//...

}

}

So, GlobalFilter is retrieved from the services registration, and, if it is a filter, it will behave accordingly to the context where it is located, in this case, it is the whole controller. SomeFilter, on the other hand, is just instantiated and used, no need to have it registered. Don’t forget that types passed to ServiceFilterAttribute and TypeFilterAttribute have to implement one of the filter interfaces in namespace Microsoft.AspNet.Mvc.Filters otherwise an exception is thrown.

Models

Model classes are declared as parameters to action methods in an MVC controller. There’s a binding mechanism that fills their properties automatically, but we can also use dependency injection here.

First, the whole model can come from dependency injection:

public IActionResult Index([FromServices] IMyService service)

{

//...

}

Or, at least, some properties of the model:

public IActionResult Update(Model model)

{

//...

}

publicclass Model

{

[FromServices]

public IMyService Service { get; set; }

//...

}

Views

MVC views can also take injected services, through the @inject directive:

@inject IMyService service;

<p>@service.Serve()</p>

View Components

View components, introduced in ASP.NET MVC Core, can also be injected in pretty much the same way as controllers:

publicclass MyServiceViewComponent : ViewComponent

{

public MyServiceViewComponent(IMyService service)

{

//do something with the service

}

publicstring Invoke()

{

//...

}

}

Tag Helpers

Tag helpers, like view components and controllers, also support constructor injection:

The key here is to create an instance of the service provider we want to use, maybe leveraging on the one produced from the service collection (BuildServiceProvider method), and return it here. Of course, if it has more features and lifetimes than the default one, you are free to use them all. The only contract it has to comply to is that of IServiceProvider.

Dependency Resolution

While running your MVC application, you can explicitly ask for services registered in the global (the default or your own) service provider. The HttpContext class exposes a RequestServices property; here you will find the custom service provider that you returned in Configure*Services, or ASP.NET Core’s built-in one. Whenever you have a reference to the current HttpContext (controllers, view components, tag helpers, views, middleware, filters), you get it as well. The “old” ApplicationServices was removed in recent commits, so it won’t make it to the final version of ASP.NET Core and you shouldn’t be using it.

Conclusion

The dependency injection mechanism was substantially changed in ASP.NET Core. The only identical feature seems to be constructor injection, and it is understandable, since it’s what most people should be using anyway. Now every moving part of ASP.NET Core is injectable through the same mechanism, which I think is a good thing. The problems so far have been the relative instability in the ASP.NET Core, things have been changing a lot, and there is still no light at the end of the tunnel.

Introduction

Some of you may remember Postal.NET from my previous posts (here, here and here). In a nutshell, it is a framework I built for writing decoupled applications in .NET, in a publish-subscribe way. It is available as open source in GitHub (do have a look at the README file) and available in Nuget.

I recently added request-response synchronous support. This is so that two parties, without knowing exactly who they are, can engage in a direct conversation. Other enterprise buses support this feature as well.

So, with that in mind, let’s recap all of the messaging patterns we have in Postal.NET. Remember that at least you need to grab the Postal.NET Nuget package.

Publish-Subscribe

OK, this is easy: someone subscribes to a channel-topic pair and someone else publishes a message to it, either synchronously or asynchronously: