又学一招——依赖注入错误

前端之家收集整理的这篇文章主要介绍了又学一招——依赖注入错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

读取配置文件中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
强引用到启动项目下面即便代码中未使用该程序集的内容也需要引用,因为配置文件解析的时候会使用。
原文链接:https://www.f2er.com/javaschema/283610.html

猜你在找的设计模式相关文章