lundi 17 août 2020

Use AutoFac to resolve generic types through a factory

I have a factory that creates and caches different types of settings.

public ISetting<TSetting> Create<TSetting>() where TSetting : new()
{
     ... Returns new or cashed ISetting<TSetting>
}

At the moment all my classes that require settings are injected with the factory itself.

public ApplicationSettingsViewModel(ISettingFactory settingFactory)
{
}

Which are then used to create the instance of the settings type they require, this is for several reason not a good way of doing it (mocking overhead during testing, passing of an object that will be instantly dropped, etc). For this reason i would like to instead be able to inject the settings itself directly into the class.

To accomplish this the DI (Autofac in my case) need to somehow know how to construct the object using the factory. This has lead me to the Delegate Factories that it seem to support, but also seem to not be exactly what im after.

I implemented a delegate into the factory class that represents the Create method. Next i added it to my container as suggested in the documentation.

builder.RegisterType<SettingFactory>();

Thus far this works fine, but to actually use it inside my classes i require a dependency on SettingFactory.Factory which can then be used to do something like factory.Create(); Although this works, it's by no means better then injecting the Factory itself.

builder.RegisterType<SettingFactory>().As<ISettingFactory>().SingleInstance();

The preferred way would be that i'm able to have a dependency on ISettings and have AutoFac resolve this through an instance of ISettingFactory.Create

Aucun commentaire:

Enregistrer un commentaire