我试图在Ninject上重现以下温莎配置。 我知道ninject有一个工厂扩展,但它远离windsor的字典适配器。
WindsorContainer container = new WindsorContainer();
container.AddFacility<Castle.Facilities.FactorySupport.FactorySupportFacility>();
container.Register(
Component.For<IApplicationSettings>().UsingFactoryMethod(
() => new DictionaryAdapterFactory()
.GetAdapter<IApplicationSettings>(ConfigurationManager.AppSettings)));
有没有人知道ninject的工厂扩展可以进行字典改编?
答案 0 :(得分:2)
工厂扩展程序允许您提供自己的IInstanceProvider
。您可以使用它来从配置中返回值:
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel();
kernel.Bind<IApplicationSettings>().ToFactory(() => new AppSettingProvider());
var settings = kernel.Get<IApplicationSettings>();
Console.WriteLine("One: " + settings.One);
}
}
public interface IApplicationSettings
{
string One { get; }
int Two { get; }
bool Three { get; }
}
public class AppSettingProvider : Ninject.Extensions.Factory.IInstanceProvider
{
public object GetInstance(IInstanceResolver instanceResolver, MethodInfo methodInfo, object[] arguments)
{
string key = methodInfo.Name;
if (key.StartsWith("get_"))
key = key.Substring(4);
string value = ConfigurationManager.AppSettings[key];
return Convert.ChangeType(value, methodInfo.ReturnType);
}
}