读取配置文件中Unitiy的配置信息:
public static class IocContext { /// <summary>Unity容器</summary> private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() => { var container = new UnityContainer(); container.LoadConfiguration("container"); return container; }); /// <summary>Unity容器实例</summary> public static IUnityContainer Instance { get { return container.Value; } } }在start中调用
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(GTAPI.App_Start.UnityWebApiActivator),"Start")] namespace GTAPI.App_Start { /// <summary>Provides the bootstrapping for integrating Unity with WebApi when it is hosted in ASP.NET</summary> public static class UnityWebApiActivator { /// <summary>Integrates Unity when the application starts.</summary> public static void Start() { // Use UnityHierarchicalDependencyResolver if you want to use a new child container for each IHttpController resolution. // var resolver = new UnityHierarchicalDependencyResolver(UnityConfig.GetConfiguredContainer()); var container = IocContext.Instance; var resolver = new UnityDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = resolver; } } }
配置文件配置如下:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <!-- 搜索别名注册 --> <!-- <assembly name="Jurassic.Sooil.SearchService"/>--> <alias alias="ISearch" type="So.ISearch.ISearch,So.ISearch" /> <alias alias="Search" type="So.Search.ESSearch,So.Search" /> <alias alias="IQuery" type="So.ISearch.IQuery,So.ISearch" /> <alias alias="Query" type="So.Search.MongoSearch,So.Search" /> <container name="container"> <!-- 搜索注册 --> <register type="ISearch" mapTo="Search"> <lifetime type="transient"/> </register> <register type="IQuery" mapTo="Query"> <lifetime type="transient"/> </register> </container> </unity>
运行报错,如上图。原因是So.Search程序集没有引用进来,在bin目录下面找不到对应的命名空间,所以无法解析Search别名,需要将So.Search