A SpecFlow plugin that provides a generic way to implement a custom DI container
- Create a class that implements the
IGenericContainer
interface and wraps your DI container. - Create a class that contains a static function with the
ScenarioDependenciesAttribute
that configures the container, and returns yourIGenericContainer
implementation.
public class SimpleInjectorContainer : IGenericContainer
{
private readonly Container _container;
public SimpleInjectorContainer(Container container)
{
_container = container;
}
public void Register<TService>(Func<TService> instanceCreator)
where TService : class
{
_container.Register(instanceCreator);
}
public object Resolve(Type bindingType)
{
return _container.GetInstance(bindingType);
}
public TService Resolve<TService>()
where TService : class
{
return _container.GetInstance<TService>();
}
}
public static class Dependencies
{
[ScenarioDependencies]
public static IGenericContainer CreateContainer()
{
var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.Options.DefaultLifestyle = Lifestyle.Singleton;
// Add your registrations here
foreach (var type in typeof(Dependencies).Assembly.GetTypes().Where(t => Attribute.IsDefined(t, typeof(BindingAttribute))))
{
container.Register(type);
}
return new SimpleInjectorContainer(container);
}
}