Continuous integration with Atlassian Bamboo

The continuous integration is a frequent theme in the application development, expecially in the projects with many developers involved that work on differents components of the application.

Just because the developers works on different features, a process that integrate the new code frequently in project and verify that all the dependencies of that are working yet is recommended.

A practice to integrate daily the new code in the shared project repository avoid problems like integration hell, where a developer has troubles to integrate code of another developer, that worked isolated for a long period.

Again, a process that manage this integration allow us to introduce in this phase the automatic tests and discover eventually regressions in the code modified.

There are different products to manage the continuous integration process and one of those is Bamboo, a product owned by Atlassian and in this post I want to talk about the configuration of the continuous integration on a .NET project with a bunch of tests implemented with NUnit.

Server configuration

Before to proceed with a project configuration we need to take care about the executables that Bamboo will needs to execute the process.

In my case I need the MSBuild and NUnit executables and I can configure them in the server capabilities section of the Bamboo configuration:

configuration7

In my case I use the MSBuild installed with Visual Studio, but you can download that from this url.

The NUnit console is the executable used for the tests execution and you can find it here.

Plan

When I need to configure a new project in Bamboo, I need to do a new plan.

A plan is composed by one or more stages; for example in my case I have a build stage, a test stage and a deploy stage.

In the stages I will create the jobs that will do some stuff.

In the plan configuration I need to take care about the referenced repository, that is the repository where Bamboo will load the source code:

configuration5

In my case I have specified the url of a GitHub repository.

Another thing that I can do is define a trigger for the plan, that is an event after which the plan execution will be fired.

I define a branch that Bamboo will polling for new changes:

configuration6

Every time a new commit will be pushed on the master branch, the plan will be executed.

Build

Now I configure the Solution Build job in the Build stage; every job is composed by one or more tasks and in this case I have three tasks.

The first one is the Source Code Checkout, that is the phase where Bamboo get the source code from the repository and copy all the content in his working directory (locally on the server where is installed).

The second one is a Script configuration, in my case I need to restore some nuget packages before to build the project; I do that by writing a script that launch the nuget executable with the option restore:

configuration8

You can find the nuget executable download here.

The last step is the MSBuild task and we use the executable configured above:

configuration9

Another thing that we can do in the job configuration is define an artifact, thus the output of the job will be available for the next jobs:

configuration10

In this way, we speedup the next job because it won’t need to checkout the repository again.

Test

The test job is more simple, because it has the source code already available and it has only the test runner:

configuration11

Again here we use the other executable configured above and we have only to specify the dll of the test project.

We don’t forget to configure the artifact for the job and use that produced in the previous job:

configuration12

Deploy

The last stage is the deploy.

To have a clean situation I do again a Source Code Checkout and than I  execute a powershell script:

configuration13

The script was explained in the previous post and deal with some stuff like build, apply a version to the assembly and copy the result in a shared directory.

That’s all, when you’ll run the plan, the result (if the project is ok :))) will looks like this:

configuration4

 

Advertisements
Continuous integration with Atlassian Bamboo

Mocking Entity Framework DbContext with Moq

When we have to test methods that involves Entity Framework, a typical choice that we have to face is use integration tests, with an effective database, or unit tests.

If we choice the first option, with a database like SQL LocalDB, we’ll have performance problems because the cost of the database creation and the data inserts in the test startup is very high, and in order to guarantee the initial conditions we’ll have to do it for each test.

What we can do is use a mock framework that help us to mockup the entity framework context; it would be an in-memory db context, like the in-memory db context of .NET Core, that we have seen in this post.

The factory

In pratice, mocking a class means substitute the real implementation of a method with our custom behaviour; what we can do for every method of the class is setup returns values of the method; therefore we don’t need the real implementation of the class, we have mocked the methods.

In our case, we can setup the EF DbSet with an in-memory list and the methods that use the context will no longer need the real database, they will use our lists provided with the mock.

Anyway, before to do it we have another problem; how we can provide our in-memory db context to the methods that we need to test?

In the real world, it’s likely that the context will be instantiated with the using statement in every method, like this:


public async Task<List<Person>> GetPersons(string query)
{
using (var db = new Context())
{
.....
}
}

This is a problem, because we are not able to inject our mocked context in the class.

But we can solve it with a Factory service, a singleton service that returns instances of the db context:


public class ContextFactory
{
private Type _dbContextType;
private DbContext _dbContext;

public void Register<TDbContext>(TDbContext dbContext) where TDbContext : DbContext, new()
{
_dbContextType = typeof(TDbContext);
_dbContext = dbContext;
}

public TDbContext Get<TDbContext>() where TDbContext : DbContext, new()
{
if (_dbContext == null || _dbContextType != typeof(TDbContext))
{
return new TDbContext();
}

return (TDbContext)_dbContext;
}
}

We have two methods, with the Register method we can setup a specific db context implementation; with the Get method we can get an instance of a db context, that is the registered implementation if we have one, otherwise the default implementation.

We can now inject this service as a dependency and use it:


public class PersonService
{
private readonly ContextFactory _contextFactory;

public PersonService(ContextFactory contextFactory)
{
_contextFactory = contextFactory;
}

public async Task<List<Person>> GetPersons(string query)
{
using (var db = _contextFactory.Get<Context>())
{
return await db.Persons.Where(p => p.TaxCode.Contains(query) || p.Firstname.Contains(query) || p.Surname.Contains(query)).ToListAsync();
}
}
}

Now we are ready to mock the EF context.

The mock

The framework that I use for this purphose is moq and I can install it with nuget:

install-package moq

It’s likely that you use async methods of entity framework; if yes, in order to mock we need to create an in-memory DbAsyncQueryProvider, and you can find the implementation here.

The Unit Testing used for this example is NUnit and I can configure the mocked context in the setup method; the first step is prepare a list of queryable objects:


[SetUp]
public void Setup()
{
var persons = new List<Person>() {
new Person() { TaxCode = "taxcode1", Firstname = "firstname1", Surname = "surname1" },
new Person() { TaxCode = "taxcode2", Firstname = "firstname2", Surname = "surname2" }
};
var queryable = persons.AsQueryable();
}

Now I’m ready to setup the mock:


MockSet = new Mock<DbSet<Person>>();

MockSet.As<IQueryable<Person>>().Setup(m => m.Expression).Returns(queryable.Expression);
MockSet.As<IQueryable<Person>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
MockSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator);

MockSet.As<IQueryable<Person>>().Setup(m => m.Provider).Returns(new AsyncQueryProvider<Person>(queryable.Provider));
MockSet.As<IDbAsyncEnumerable<Person>>().Setup(m => m.GetAsyncEnumerator()).Returns(new AsyncEnumerator<Person>(queryable.GetEnumerator()));

In order to mock an IQueryable, I have to setup returns values for Expression method, ElementType and GetEnumerator; every time these methods will be invoked in the queries executions, the values that I setup in the Returns expression will be returned.

I need to do the same operations for Provider method and GetAsyncEnumerator, but, since async methods are involved, I need to use the custom classes AsyncQueryProvider and AsyncEnumerator of the in-memory DbAsyncQueryProvider.

The mock for the Add and Remove operations are simplier:


MockSet.Setup(m => m.Add(It.IsAny<Person>())).Callback((Person person) => persons.Add(person));
MockSet.Setup(m => m.Remove(It.IsAny<Person>())).Callback((Person person) => persons.Remove(person));

Since Add and Remove methods returns nothing, we use Callback methods instead of Returns.

The last step is setup the factory service context with the mocked version:


MockContext = new Mock<Context>();
MockContext.Setup(m => m.Persons).Returns(MockSet.Object);

var contextFactory = new ContextFactory();
contextFactory.Register(MockContext.Object);
PersonService = new PersonService(contextFactory);

First of all I setup the DbSet of the mocked context with the mocked DbSet.

Then I register the mocked context in the factory service and then I pass the factory service as a dependency of the service to be test.

With these lines of code I have mocked the entity framework context with an in-memory instance and leveraging the context factory I was able to inject the mocked context to the service.

You can find the source code here.

 

Mocking Entity Framework DbContext with Moq

Register and test per-request services with Autofac

When we develop web application, like ASP.NET applications, we often need to implement a service with some informations related to the user request, such as session/account infos.

In this case, the service will be tied to the web request lifecycle and there will be an instance of the service for each request.

Autofac help us to manage the instances and the life cycles of these services.

Service

We can develop a simple service that we use for our tests:


public class AccountService
{
private ITokenService _tokenService;

public AccountService(ITokenService tokenService)
{
_tokenService = tokenService;
}
}

Module

In order to register the service, we use an Autofac module:


public class PerRequestModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AccountService>()
.AsSelf()
.InstancePerRequest()
.WithParameter(new ResolvedParameter(
(pi, ctx) => pi.ParameterType == typeof(ITokenService),
(pi, ctx) => ctx.ResolveKeyed<ITokenService>("singletonTokenService")
));
}
}

The service was defined has InstancePerRequest; we also specified explicitly the implementation of the parameter interface.

And register it in the Autofac container:


var builder = new ContainerBuilder();
...
builder.RegisterModule(new PerRequestModule());
...
containerBuilder = builder.Build();

Test methods

Now, the last step is the test methods:


[Test]
public void should_is_not_the_same_instance_for_different_requests()
{
AccountService accountService1, accountService2;

using (HttpRequestMessage request = new HttpRequestMessage())
{
request.SetConfiguration(httpConfiguration);
var dependencyScope = request.GetDependencyScope();
accountService1 = dependencyScope.GetService(typeof(AccountService)) as AccountService;
}

using (HttpRequestMessage request = new HttpRequestMessage())
{
request.SetConfiguration(httpConfiguration);
var dependencyScope = request.GetDependencyScope();
accountService2 = dependencyScope.GetService(typeof(AccountService)) as AccountService;
}

ReferenceEquals(accountService1, accountService2).ShouldBeEquivalentTo(false);
}

[Test]
public void should_be_able_to_resolve_instance_per_request()
{
using (HttpRequestMessage request = new HttpRequestMessage())
{
request.SetConfiguration(httpConfiguration);
var dependencyScope = request.GetDependencyScope();
AccountService service = dependencyScope.GetService(typeof(AccountService)) as AccountService;

service.Should().NotBeNull();
}
}

In order to be able to test a per-request service, we need an instance of the HttpRequestMessage class and set the configuration with the httpConfiguration defined in the Autofac container; then we can use the request scope to get an instance of our services and make the test.

You can find the source code here.

Register and test per-request services with Autofac

Registering of the ASP.NET MVC Controllers with Autofac

One of the capabilities of Autofac is the integration with the ASP.NET applications.

ASP.NET MVC is a framework thinked to supports the dependency injection, and so we can use Autofac to register the modules that compose the application, such as the controllers.

Therefore, let’s start by implementing the controllers of the application, then we ‘ll add the Autofac module that define the controllers registration.

Controllers

We implement two controllers, a Controller and an ApiController:

public class HomeController : Controller
 {
 LoggerService _loggerService;

public HomeController(LoggerService loggerService)
 {
 _loggerService = loggerService;
 }
 }

The second one is the Web Api:

public class AccountController : ApiController
 {
 LoggerService _loggerService;

 public AccountController(LoggerService loggerService)
 {
 _loggerService = loggerService;
 }
 }

Autofac module

The first step is install the two autofac packages needed for the integration with ASP.NET:

install-package Autofac.Integration.Mvc
install-package Autofac.Integration.WebApi

Now we can register the controllers with an Autofac module:

public class PerRequestModule : Module
 {
 protected override void Load(ContainerBuilder builder)
 {
 var controllersAssembly = Assembly.GetAssembly(typeof(HomeController));
 var apiControllersAssembly = Assembly.GetAssembly(typeof(AccountController));

 builder.RegisterControllers(controllersAssembly);
 builder.RegisterApiControllers(apiControllersAssembly);
 }
 }

By using the reflection, we can register all the controllers in one shot.

The module needs to be registered in the autofac container:

var builder = new ContainerBuilder();
....
builder.RegisterModule(new PerRequestModule());
...
containerBuilder = builder.Build();

DependencyResolver.SetResolver(new AutofacDependencyResolver(containerBuilder));

httpConfiguration = new HttpConfiguration
{
DependencyResolver = new AutofacWebApiDependencyResolver(containerBuilder)
};

We built the container and passed that to the AutofacDependencyResolver (Controller) and to the AutofacWebApiDependencyResolver (ApiController).

Tests

Now we can implement the test methods:

public class PerRequestTests : BaseTests
{
[Test]
public void should_be_able_to_resolve_mvc_controller()
{
using (var scope = containerBuilder.BeginLifetimeScope())
{
var controller = scope.Resolve<HomeController>();
controller.Should().NotBeNull();
}
}

[Test]
public void should_be_able_to_resolve_api_controller()
{
using (var scope = containerBuilder.BeginLifetimeScope())
{
var controller = scope.Resolve<AccountController>();
controller.Should().NotBeNull();
}
}
}

As you can see, we initialized a new lifetime scope and tried to resolve the controllers.
You can find the source code here.

Registering of the ASP.NET MVC Controllers with Autofac

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.

 

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