Autofac - VianneyDoleans/Teia-Tests-Documentation GitHub Wiki
Autofac
As said inside this documentation, autofac enables dependency injection inside your code.
Here is an example :
The code :
[TestFixture]
public class ConfigServiceTests : DatabaseEnabledTestsBase
{
private IConfigService _configService;
private IRepository<EntityRecord> _repositoryEntityRecord;
private IRepository<UniverseRecord> _repositoryUniverseRecord;
private IRepository<SceneRecord> _repositorySceneRecord;
private SceneRecord sceneRecord;
public override void Register(ContainerBuilder builder)
{
builder.RegisterType<ConfigService>().As<IConfigService>();
builder.RegisterType<Repository<EntityRecord>>().As<IRepository<EntityRecord>>();
builder.RegisterType<Repository<UniverseRecord>>().As<IRepository<UniverseRecord>>();
builder.RegisterType<Repository<SceneRecord>>().As<IRepository<SceneRecord>>();
}
public override void Init()
{
base.Init();
_configService = _container.Resolve<IConfigService>();
_repositoryEntityRecord = _container.Resolve<IRepository<EntityRecord>>();
_repositoryUniverseRecord = _container.Resolve<IRepository<UniverseRecord>>();
_repositorySceneRecord = _container.Resolve<IRepository<SceneRecord>>();
}
}
Register
public override void Register(ContainerBuilder builder)
ContainerBuilder
object is the object in which we will add the dependency injections.
For adding a dependency, we do :
builder.RegisterType<ConfigService>().As<IConfigService>();
- Here,
ConfigService
is declared as the constructor class to use whenIConfigService
is called inside the code. - We could add anything instead of
ConfigService
, it just have to have the same method declaration thatIConfigService
interface.
Resolve
_configService = _container.Resolve<IConfigService>();
You just have to know to understand the exemple that previously in the code, from inheritance DatabaseEnabledTestsBase for class ConfigServiceTests
, there's lines was realized :
protected IContainer _container;
_container = builder.Build();
So, with _configService = _container.Resolve<IConfigService>();
we said that our variable _configService
is fill with an instance of IConfigService
, which in real, are a ConfigService, as we declared previously inside the code (register).
- So now, we have an
IConfigService _configService
instanciated, and we can use it into your tests.
To go futher
There is a many other ways to use autofac, with other functionnalities of it. Here is just an example to get start with autofac.
To go futher, you can read the official documentation or look for some more advance tutorials / articles.