Services lifetime scope with Autofac

Basically when we resolve a component with Autofac, we could register the object instance in the root container; this is not the best practice, because these components will never be disposed as long as the container lives, that normally is the lifetime of the application.

Then, the root container will hold the references until the application shutdown, and this could be cause memoty leaks.

A better approach is the using of the lifetime scopes, that help us to define an area where the service can be shared with other components and disposed at the end.

Let’s start defining the classes to be used as services in the Autofac configuration.

Services

We can use two simple class, a CustomerService class and an OrdersService:


public class CustomerService
{
public CustomerService() { }
}


public class OrdersService
{
private ITokenService _tokenService;

public OrdersService(ITokenService tokenService)
{
this._tokenService = tokenService;
}

}

The OrdersService accepts in the constructor an ITokenService and we have an implementation of that:


public class PerDependencyTokenService : ITokenService
 {
 private Guid _token { get; set; }

public Guid GetToken()
 {
 if (_token == Guid.Empty)
 _token = Guid.NewGuid();

return _token;
 }
 }

Now we can define the services registration, let’s start creating the Autofac modules.

Modules

First of all, we need to register the PerDependencyTokenService and we must identify it in order to distinguish this service from the others that implements the ITokenService interface:


public class PerDependencyModule : Module
 {
 protected override void Load(ContainerBuilder builder)
 {

builder.RegisterType<PerDependencyTokenService>()
 .AsSelf()
 .AsImplementedInterfaces()
 .Keyed<ITokenService>("perDependencyTokenService");
 }
 }

We registered the service as Keyed, and we identified that with a specific tag.

Now we can register the other services:


public class PerLifetimeScopeModule : Module
 {
 protected override void Load(ContainerBuilder builder)
 {
 builder.RegisterType<OrdersService>()
 .AsSelf()
 .InstancePerLifetimeScope()
 .WithParameter(new ResolvedParameter(
 (pi, ctx) => pi.ParameterType == typeof(ITokenService),
 (pi, ctx) => ctx.ResolveKeyed<ITokenService>("perDependencyTokenService")
 ));

// PER MATCHING LIFETIMESCOPE
 builder.RegisterType<CustomerService>()
 .AsSelf()
 .InstancePerMatchingLifetimeScope("scope1");
 }

}

OrderService is registered as InstancePerLifetimeScope, so an instance of this component will be unique in a specific scope.

We specify the Parameter ITokenService as well, and we tell to Autofac to resolve this with a specific key; so we are able to specify the concrete class that implements the ITokenService interface.

The second registration is about the CustomerService; this registration is slightly different from the first one, because we want to resolve the CustomerService only for the lifetime scopes that has a specific name.

Now we are going to implement the test methods that will use the services.

Test methods

The first step is register the module in the Autofac container:

builder.RegisterModule(new PerLifetimeScopeModule());

Then we can implement the test methods:

public class InstancePerLifetimeScopeTests : BaseTests
{
[Test]
public void should_is_not_the_same_instance_for_different_lifetime_scopes()
{
OrdersService ordersService1, ordersService2;

using (var scope = containerBuilder.BeginLifetimeScope())
{
ordersService1 = scope.Resolve<OrdersService>();
}

using (var scope = containerBuilder.BeginLifetimeScope())
{
ordersService2 = scope.Resolve<OrdersService>();
}

ReferenceEquals(ordersService1, ordersService2).ShouldBeEquivalentTo(false);
}

[Test]
public void should_not_be_able_to_resolve_instance_per_lifetime_scope()
{
CustomerService customerService1 = null, customerService2 = null;

try
{
using (var scope = containerBuilder.BeginLifetimeScope())
{
customerService1 = scope.Resolve<CustomerService>();

using (var scope1 = containerBuilder.BeginLifetimeScope("scope1"))
{
customerService2 = scope.Resolve<CustomerService>();
}

customerService1.ShouldBeEquivalentTo(null);
}
}
catch (Exception)
{
customerService1.ShouldBeEquivalentTo(null);
}
}

[Test]
public void should_be_able_to_resolve_instance_per_lifetime_scope()
{
CustomerService customerService1, customerService2;

using (var scope = containerBuilder.BeginLifetimeScope("scope1"))
{
customerService1 = scope.Resolve<CustomerService>();

using (var scope1 = containerBuilder.BeginLifetimeScope())
{
customerService2 = scope.Resolve<CustomerService>();
}
}

ReferenceEquals(customerService1, customerService2).ShouldBeEquivalentTo(true);
}
}

In the first method, we create two different lifetime scopes and we check that the two objects have not the same reference.

In the second one, we should not be able to resolve the CustomerService for a generic lifetime scope, because we registered this service for a scope named scope1.

So this row:

customerService1 = scope.Resolve<CustomerService>();

will throw a DependencyResolutionException.

Instead in the third method will be able to resolve the service, because we try to create an instance in a LifetimeScope named scope1; and of course, this service will be single instance for every lifetime scope that match the name.

You can find the source code here.

 

Advertisements
Services lifetime scope with Autofac

Repository pattern with Autofac

The repository pattern is one of the most popular patterns used in the applications architecture.

With Autofac we are able to manage the dependencies and the lifecycle of the repositories in our application.

So let’s starting with the implementation of a basic respository example, then we proceed with the Autofac configurations and with the test methods.

Repository implementation

The are many choices to put into practice the repository pattern.

But this is not the main topic of this post, so we can proceed with a simple implementation:


public class Product
{
public int Code { get; set; }
public string Description { get; set; }
}

public interface IProductsRepository
{
List<Product> GetProducts();
}

public class ProductsRepository : IProductsRepository
{
private string _connectionString;
private List<Product> _products { get; set; }

public ProductsRepository(string connectionString)
{
_connectionString = connectionString;

_products = new List<Product>()
{
new Product()
{
Code = 1,
Description = "Product1"
},
new Product()
{
Code = 2,
Description = "Product2"
}
};
}

public List<Product> GetProducts()
{
return _products;
}
}

The ProductRepository implements a simple interface and has a constructor that accept a connection string parameter and populates a list of products.

In the real world the repository should use the connection string to connect to a database and retrieve the products, but in this case is easier to build an in memory list.

Now we inject this repository in the services that use it:


public class ProductsService
{
private IProductsRepository _productsRepository;
private ITokenService _tokenService;

public ProductsService(IProductsRepository productsRepository, ITokenService tokenService)
{
this._productsRepository = productsRepository;
this._tokenService = tokenService;
}

public List<Product> GetProducts()
{
List<Product> products = new List<Product>();

if (_tokenService.GetToken() != Guid.Empty)
products = _productsRepository.GetProducts();

return products;
}
}

The service has a GetProducs method that returns the list of products if a specific token is valid.

Autofac configuration

Autofac can be organized in modules, each of witch will be registered in the container.

In this case, we can implement a module for all the objects registered as PerDependency:


public class PerDependencyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
var repositoriesAssembly = Assembly.GetAssembly(typeof(ProductsRepository));
builder.RegisterAssemblyTypes(repositoriesAssembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces()
.WithParameter(
new TypedParameter(typeof(string), ConfigurationManager.ConnectionStrings["Context"].ToString())
);
}
}

By default, Autofac registers the components as per dependency, that means that a unique instance of the object will be created for each request.

With the first row we retrieve the list of the repository objects in the assembly, by checking that in the name of the class the word Repository is present.

Then we say autofac that the object shall be registered as the implemented interface; if you remember, in the constructor of the ProductService we defined the repository parameter by using the interface and not the relative concrete class.

The last part define the parameter that the repository needs, that is the connection string.

The second module that we create is the SingleInstanceModule:


public class SingleInstancesModule : Module
{
protected override void Load(ContainerBuilder builder)
{

builder.RegisterType<ProductsService>()
.AsSelf()
.SingleInstance();
}
}

We register the ProductService as single instance because we want that only one instance for this service exists in the application.

Then we register the modules in the Autofac container.

Because we want to test the configuration, we can make a BaseTest class with NUnit, and build the container in the Setup method.


[TestFixture]
public class BaseTests
{
protected IContainer containerBuilder;
protected HttpConfiguration httpConfiguration;

[SetUp]
public void Setup()
{
var builder = new ContainerBuilder();

// SINGLE INSTANCES
builder.RegisterModule(new SingleInstancesModule());

// PER DEPENDENCY
builder.RegisterModule(new PerDependencyModule());

containerBuilder = builder.Build();
}

[TearDown]
public void TearDown()
{
containerBuilder.Dispose();
}
}

With the RegisterModule method we are able to register an entire module defined.

Test methods

Here we go, now we can implement test methods to check that our configuration is correct.

First of all, we check the ProductRepository registration:


public class PerDependencyTests : BaseTests
{

[Test]
public void should_be_able_to_resolve_instance_per_dependency()
{
using (var scope = containerBuilder.BeginLifetimeScope())
{
var result = scope.Resolve<IProductsRepository>();
result.Should().NotBeNull();
}
}

[Test]
public void should_not_be_able_to_resolve_instance_per_dependency()
{
ProductsRepository repository = null;

try
{
using (var scope = base.containerBuilder.BeginLifetimeScope())
{
repository = scope.Resolve<ProductsRepository>();
repository.ShouldBeEquivalentTo(null);
}
}
catch (Exception)
{
repository.ShouldBeEquivalentTo(null);
}
}
}

For every test method we create a LifetimeScope that is useful to create a concrete instance of the repository.

In the first test method we try to resolve the IProductRepository interface, and the result is true.

In the second one, we try to resolve the concrete class, and we should not be able to do it, because, as you remember, we registered the ProductRepository as the implemented interface.

The ProductService registration test methods might look like these:


public class SingleInstanceTests: BaseTests
{

[Test]
public void should_return_the_products_list()
{
using (var scope = containerBuilder.BeginLifetimeScope())
{
var productsService = scope.Resolve<ProductsService>();
var result = productsService.GetProducts();

result.Should().NotBeNull();
result.Should().NotBeEmpty();
}
}

[Test]
public void should_is_the_same_single_instance()
{
ProductsService productsService1, productsService2;

using (var scope = containerBuilder.BeginLifetimeScope())
{
productsService1 = scope.Resolve<ProductsService>();
}

using (var scope = containerBuilder.BeginLifetimeScope())
{
productsService2 = scope.Resolve<ProductsService>();
}

ReferenceEquals(productsService1, productsService2).ShouldBeEquivalentTo(true);
}
}

The first method check that a list of products is returned.

The second one verify that for different lifetime scopes, the service instance is the same.

You can find the source code here.

 

Repository pattern with Autofac

Register a singleton service with Autofac

Autofac is a popular and very useful IoC container, a tool that help us to manage the dependency injection in our application.

What we want from a IoC container is the ability to instantiate the objects needed in different contexts and situations and define configurations, without worry about who and when instantiate these objects.

Of course, the target application need to be ready to host an IoC container, that means all the components of the application will need to be able to receive their dependencies as inputs.

Moving on, one of a common cases where we use an IoC container is to manage a singleton service.

The old school did solve this situation without an IoC container, but defining the service as static and using it directly in the objects that depends upon it.

With Autofac this service will be defined as a non static object and injected in the constructor as dependence.

This is the first of series of post that I hope help to understand the power of Autofac and to discover more in detail a bunch of features useful for our applications.

Application architecture

Lets starting with the development of a example application that will using Autofac.

In this application we need to implement and share a singleton service; the scope of this service is generate a token and provide it to the dependent services.

So, the token service implement an interface:


public interface ITokenService
 {
 Guid GetToken();
 }

And the implementation is like this:

public class SingletonTokenService : ITokenService
 {
 private Guid _token { get; set; }

 public Guid GetToken()
 {
 if (_token == Guid.Empty)
 _token = Guid.NewGuid();

 return _token;
 }
 }

This is a very simple piece of code so far.

Now you can implement the ProductService, that need to use TokenService:

public class ProductsService
 {
 private IProductsRepository _productsRepository;
 private ITokenService _tokenService;

 public ProductsService(IProductsRepository productsRepository, ITokenService tokenService)
 {
 this._productsRepository = productsRepository;
 this._tokenService = tokenService;
 }

 public List<Product> GetProducts()
 {
 List<Product> products = new List<Product>();

 if (_tokenService.GetToken() != Guid.Empty)
 products = _productsRepository.GetProducts();

 return products;
 }
 }

The service receives in the constructor the dependencies objects and assign them to private objects.

The GetProducts method check if the token is valid and returns the list of products.

Now we need to configure Autofac in order to provide the services.

Autofac container

Autofac has a container builder that we use to define the rules for the objects instantiation:

var builder = new ContainerBuilder();

builder.RegisterType<SingletonTokenService>()
 .AsSelf()
 .AsImplementedInterfaces()
 .SingleInstance();

builder.RegisterType<ProductsService>()
 .AsSelf()
 .SingleInstance();

containerBuilder = builder.Build();

You can notice SingleInstance option, that means these services are singleton; furthermore, the SingleTokenService has the option AsImplementedInterface that allow to resolve all the dependencies that refer to the interface implemented by the service (in the constructor of the ProductService we refer to the interface, not to the implemented class).

Resolve the service

The last step is resolve the ProductService.

We expect that once resolved, will exist only a single instance of the service; we can make a simple test method using NUnit.

public void should_is_the_same_instance()
{
ProductsService productsService1, productsService2;

using (var scope = this.containerBuilder.BeginLifetimeScope())
{
productsService1 = scope.Resolve<ProductsService>();
}

using (var scope = this.containerBuilder.BeginLifetimeScope())
{
productsService2 = scope.Resolve<ProductsService>();
}

object.ReferenceEquals(productsService1, productsService2).ShouldBeEquivalentTo(true);
}

In order to simulate two request, we use the BeginLifeTimeScope method, that create a separate scope for the instances; with the Resolve method we tell to Autofac to resolve and create an instance of a specific object, with the rules specified in the container.

In the last row we check that the two objects have reference equality.

You can find the source code here.

Register a singleton service with Autofac

Typescript checking with TSLint

TSLint is a linter for Typescript, then a program that analyse our code to find potential errors and make the code more readable.

The very nice feature is that TSLint has a separate json file, named tslint.json, to configure the analisys process and allow us to setup the rules; we need to put this file in the root of the project and tslint will use that to read the settings.

Once defined the configuration, we’ll embed this in a task runner process like Gulp and we’ll have a complete process to fix all the typescript projects.

TSLint installation

First of all, we need to install the TSLint npm package and the Gulp TSlint plugin:

npm install tslint –save-dev

npm install gulp-tslint –save-dev

These packages will be added to the package.json file in the root of the project.

TSLint configuration

You need to add tslint.json file in the root of the project and compile that; there are many options that you can specify, the nomenclature is clear and it’s very easy to understand what a specific option means.

After some test, this is the configuration file applied:

{
"rules": {
"align": [ true, "arguments", "parameters", "statements" ],
"class-name": true,
"comment-format": [ true, "check-lowercase", "check-space" ],
"curly": true,
"eofline": true,
"indent": [ true, "spaces" ],
"interface-name": [ true, "always-prefix" ],
"jsdoc-format": true,
"label-position": true,
"label-undefined": true,
"member-access": true,
"member-ordering": [
true,
{
"order": "fields-first"
}
],
"no-any": false,
"no-arg": true,
"no-conditional-assignment": true,
"no-consecutive-blank-lines": true,
"no-construct": true,
"no-constructor-vars": true,
"no-debugger": true,
"no-duplicate-key": true,
"no-duplicate-variable": true,
"no-empty": true,
"no-eval": true,
"no-inferrable-types": false,
"no-internal-module": true,
"no-require-imports": true,
"no-shadowed-variable": true,
"no-string-literal": true,
"no-switch-case-fall-through": true,
"no-trailing-whitespace": true,
"no-unreachable": true,
"no-unused-expression": true,
"no-unused-variable": true,
"no-use-before-declare": true,
"no-var-keyword": true,
"no-var-requires": true,
"one-line": [ true, "check-catch", "check-else", "check-finally", "check-open-brace", "check-whitespace" ],
"quotemark": [ true, "double" ],
"radix": true,
"semicolon": [ true, "always" ],
"switch-default": true,
"triple-equals": true,
"typedef": [ true, "arrow-parameter", "call-signature", "member-variable-declaration", "parameter", "property-declaration", "variable-declaration" ],
"use-strict": [ true, "check-function", "check-module" ],
"variable-name": [ true, "check-format", "allow-leading-underscore", "ban-keywords" ],
"whitespace": [ true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type" ]
}
}

TSLint gulp task

The Gulp plugin need to be added to the gulpfile.js file:


'use strict';

var gulp = require('gulp'),
...
tslint = require('gulp-tslint')

gulp.task('tslint', function () {
gulp.src(config.ts)
.pipe(tslint({
formatter: 'verbose'
}))
.pipe(tslint.report({
emitError: true,
sort: true,
fullPath: true,
reportLimit: 10
}))
});

We have some options that we can specify for the report, the reportLimit is very useful when you execute the task for the first time and the report is too long.

Now, you can execute the task with the command:

gulp tslint

In the console the analisys report will be showed:

tslint_report

You can find the project here.

 

 

 

 

 

 

Typescript checking with TSLint