我有以下Unity代码 -
运行时的InjectionFactory构造函数如何获得实际的容器实例(c)?
container.RegisterType<DbProviderFactory>(new InjectionFactory(c =>
DbProviderFactories.GetFactory(c.Resolve<IApplicationSettings>().GetValue("DatabaseProviderName"))));
完成后,请参阅下面的客户端类定义 -
public static class IocConfig
{
public static void RegisterDependencies(IUnityContainer container)
{
IocConfig.container = container;
container.RegisterType<IApplicationSettings, ConfigAppSettings>();
container.RegisterType<IViewModelMapper, SimpleRoomViewModelMapper>();
container.RegisterType<IRoomRepository, AdoNetRoomRepository>();
container.RegisterType<RepositoryRoomViewModelService>(new ContainerControlledLifetimeManager());
container.RegisterType<IRoomViewModelReader, RepositoryRoomViewModelService>();
container.RegisterType<IRoomViewModelWriter, RepositoryRoomViewModelService>();
container.RegisterType<DbProviderFactory>(new InjectionFactory(c =>
DbProviderFactories.GetFactory(c.Resolve<IApplicationSettings>().GetValue("DatabaseProviderName"))));
}
private static IUnityContainer container;
}
以下是InjectionFactory的定义 -
public class InjectionFactory : InjectionMember
{
private readonly Func<IUnityContainer, Type, string, object> factoryFunc;
/// <summary>
/// Create a new instance of <see cref="InjectionFactory"/> with
/// the given factory function.
/// </summary>
/// <param name="factoryFunc">Factory function.</param>
public InjectionFactory(Func<IUnityContainer, object> factoryFunc)
: this((c, t, s) => factoryFunc(c))
{
}
/// <summary>
/// Create a new instance of <see cref="InjectionFactory"/> with
/// the given factory function.
/// </summary>
/// <param name="factoryFunc">Factory function.</param>
public InjectionFactory(Func<IUnityContainer, Type, string, object> factoryFunc)
{
Guard.ArgumentNotNull(factoryFunc, "factoryFunc");
this.factoryFunc = factoryFunc;
}