Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dependency injection in SpecFlow step-file

We're using Unity as our dependency injection framework.

I want to create an acceptance test and need an instance of DossierService.
Unfortunately I get the following exception:

BoDi.ObjectContainerException: 'Interface cannot be resolved [...]'

[Binding]
public class DossierServiceSteps : BaseSteps
{
    private IDossierService dossierService;

    public DossierServiceSteps(IDossierService dossierService)
    {
        this.dossierService = dossierService;
    }
}
  • What exactly is BoDi? I can't find any useful information..
  • How can I tell SpecFlow to use the normal Unity container?

Thanks in advance

Edit: I've tried using SpecFlow.Unity like so:

public static class TestDependencies
{
    [ScenarioDependencies]
    public static IUnityContainer CreateContainer()
    {
        var container = UnityConfig.GetConfiguredContainer();

        container.RegisterTypes(typeof(TestDependencies).Assembly.GetTypes().Where(t => Attribute.IsDefined(t, typeof(BindingAttribute))),
            WithMappings.FromMatchingInterface,
            WithName.Default,
            WithLifetime.ContainerControlled);

        return container;
    }
}

In UnityConfig the types are correctly registered

container.RegisterType<IDossierService, DossierService>(new InjectionConstructor(typeof(IDataService), typeof(IDossierRepository), typeof(IDbContext), true));

But I still get the same exception. When I put a breakpoint at the start of the CreateContainer() method of TestDependencies it doesn't break...

like image 409
xeraphim Avatar asked Jul 27 '26 20:07

xeraphim


1 Answers

For anyone looking for available plugins/libraries that support DI in Specflow project: https://docs.specflow.org/projects/specflow/en/latest/Extend/Available-Plugins.html#plugins-for-di-container

I prefer - https://github.com/solidtoken/SpecFlow.DependencyInjection

Example

Create DI container:

[ScenarioDependencies]
public static IServiceCollection CreateServices()
{
    var services = new ServiceCollection();

    Config config = JObject.Parse(File.ReadAllText("config.json")).ToObject<Config>();
    
    services.AddSingleton(config);
    services.AddScoped<DbConnections>();
    services.AddScoped<ApiClients>();

    return services;
}

Consume dependencies (via parameterized constructors):

[Binding]
public sealed class CalculatorStepDefinitions
{
    private readonly DbConnections dbConnections;

    public CalculatorStepDefinitions(DbConnections dbConnections) => this.dbConnections = dbConnections;

    ...
}
like image 163
Meer Avatar answered Jul 29 '26 12:07

Meer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!