鉴于某些模块本身具有依赖性,我正在努力解决如何在模块中组织我的 Autofac 组件注册。
我在接口中实现了配置数据的抽象(即web.config):
interface IConfigurationProvider
{
T GetSection<T>(string sectionName)
where T : System.Configuration.ConfigurationSection;
}
以及 ASP.NET ( WebConfigurationProvider
) 和“桌面”应用程序 ( ExeConfigurationProvider
) 的实现。
然后我的一些 autofac 模块需要 aIConfigurationProvider
作为构造函数参数,但有些不需要:
class DependentModule : Module
{
public DependentModule(IConfigurationProvider config)
{
_config = config;
}
protected override void Load(ContainerBuilder builder)
{
var configSection = _config.GetSection<CustomConfigSection>("customSection");
builder.RegisterType(configSection.TypeFromConfig);
}
private readonly IConfigurationProvider _config;
}
class IndependentModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(/* other stuff not based on configuration */);
}
}
由于RegisterType()
扩展方法不接受注册委托(Func<IComponentContext, T>
),就像这样Register()
做一样,我不能预先注册IConfigurationProvider
然后在我去注册配置中指定的类型时解决它,例如:
// this would be nice...
builder.RegisterType(c => c.Resolve<IConfigurationProvider>().GetSection<CustomConfigSection>("sectionName").TypeFromConfig);
这意味着我需要能够注册具有和不依赖于IConfigurationProvider
.
很明显如何手动实例化每个模块并注册它:
IConfigurationProvider configProvider = ...;
var builder = new ContainerBuilder();
builder.RegisterModule(new DependentModule(configProvider));
builder.RegisterModule(new IndependentModule());
using (var container = builder.Build())
{
...
}
但我不想手动实例化我的模块 - 我想扫描程序集以查找模块并自动注册它们(如本问题中所述)。所以我必须使用反射来扫描程序集的IModule
类型,并使用它Activator.CreateInstance
来制作可注册的实例。但是我怎么知道是否将 anIConfigurationProvider
作为构造函数参数传递。当其他模块有额外的或不同的依赖时会发生什么?
必须有一种更直接的方法来完成基本任务:注册在通过接口提供的某些配置中指定的类型,对吗?那么我该怎么做呢?