Unity - 将已解决的类型用作其他已解析类型中的参数

时间:2017-09-01 06:44:27

标签: c# unity-container

我在8小时内团结一致,已经想出了一些事情,但我无法找到与此相关的角度。我得到了$(document).ready(function(){ $('#signupForm').on('submit',function(e){ e.preventDefault(); $('#message').html('<i class="fa fa-spinner fa-spin" aria-hidden="true"></i>'); var data_arr=jQuery(this).serializeArray(); jQuery.ajax({ type:"POST", url:"send.php", data:data_arr, success:function(response){ //alert(data); //console.log( JSON.parse(data)); if (response=='check') { $('#message').html("<i class='fa fa-check' aria-hidden='true'></i>"); }else{ $('#message').html("<i class='fa fa-times' aria-hidden='true'></i>"); } } }); });

IResourceManager

和相应的类型:

public interface IResourceManager
{
    ILogger Logger { get; set; }
    string Path { get; set; }
}

Futhermore

public class ResourceManager : IResourceManager
{
    public ResourceManager(ILogger logger, string path)
    {
        Logger = logger;
        Path = path;
    }
    public ILogger Logger { get; set; }
    public string Path { get; set; }
}

最后

public class Logger : ILogger
{    }

我想像Singletons一样表现Logger和ResourceManager。只要在IResourceManager中没有ILogger,我就可以使用它,但我一直得到&#34;没有默认构造函数&#34;异常。

到目前为止,我有:

public ResourceManagerController(ILogger logger, IResourceManager imageResourceManager)
{}

如何注册我的类型以便ResourceManagerController的实例化成功并且public static void Register(HttpConfiguration config) { var container = new UnityContainer(); container.RegisterType<ILogger, Logger>("DefaultLogger", new ContainerControlledLifetimeManager()); container.RegisterType<IResourceManager, ResourceManager>("imageResourceManager", new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<ILogger>("DefaultLogger"), "basePath")); config.DependencyResolver = new UnityResolver(container); // Web API routes ... } Logger都用作单例?

1 个答案:

答案 0 :(得分:0)

如果要注册记录器以用作默认记录器,则不得为注册命名。 如果你想要所有的命名注册,让unity注入一个数组。

要么...

container.RegisterType<ILogger, Logger>(new ContainerControlledLifetimeManager());
container.RegisterType<IResourceManager, ResourceManager>(new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<ILogger>(), "basePath"));

public ResourceManagerController(ILogger logger, IResourceManager imageResourceManager)
{}

...或

container.RegisterType<ILogger, Logger>(new ContainerControlledLifetimeManager());
container.RegisterType<IResourceManager, ResourceManager>("imageResourceManager", new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<ILogger>(), "basePath"));

public ResourceManagerController(ILogger logger, IResourceManager[] allResourceManagers)
{}