7
我有以下接口:Autofac。如何使用自定義方法(屬性)來解析某個接口?
public interface IConfigurationProvider<TSettings> where TSettings : ISettings, new()
{
TSettings Settings { get; }
}
public interface ISettings
{
}
我有以下實現IConfigurationProvider的:
public class ConfigurationProvider<TSettings> : IConfigurationProvider<TSettings> where
TSettings : ISettings, new()
{
public ConfigurationProvider()
{
this.BuildConfiguration();
}
public TSettings Settings { get; private set; }
private void BuildConfiguration()
{
this.Settings = new TSettings();
//...load and assign properties to 'this.Settings'
//...skipped
// now 'Settings' property contains configured 'ISettings' instance
}
}
我也可以有不同的類實現 'ISettings' 界面。例如,
public class UserSettings : ISettings
{
public int SomeProperty1 { get; set; }
public int SomeProperty2 { get; set; }
}
public class CatalogSettings : ISettings
{
public int SomeProperty3 { get; set; }
public int SomeProperty4 { get; set; }
}
我用下面的代碼來配置 'ContainerBuilder':builder.RegisterGeneric(typeof(ConfigurationProvider<>)).As(typeof(IConfigurationProvider<>));
它工作正常。而爲了得到「UserSettings」我用下面的代碼:
var userSettingsProvider = builder.Resolve<IConfigurationProvider<UserSettings>>();
var userSettings = userSettingsProvider.Settings;
的問題:我應該如何配置「ContainerBuilder」這樣我就可以解決一定的「ISettings」方式如下:
var userSettings = builder.Resolve<UserSettings>();
Autofac可以嗎?
在此先感謝
感謝您的回覆。我在BuildRegistration()方法中遇到了以下編譯錯誤「無法隱式地將類型'Autofac.Builder.IRegistrationBuilder'轉換爲'Autofac.Core.IComponentRegistration'' 。 –
2011-02-01 07:23:39