In one of my projects (.NET based - using the Web API), I am using StructureMap as a dependency injection tool. The basic setup I have for it is that for each assembly where dependency injection is required, I have a dependency resolution class which extends the StructureMap Registry class. Here is a simple and clear example:

namespace Security.DependencyResolution
{
public class SecurityRegistry : Registry
{
public SecurityRegistry()
{
Scan(config =>
{
config.WithDefaultConventions();
config.AssembliesFromApplicationBaseDirectory();
config.IncludeNamespace("Data.Repositories");
config.IncludeNamespace("Security");
});
} public static void Initialize(IContainer container)
{
container.Configure(ct => ct.Scan(scan =>
{
scan.LookForRegistries();
scan.TheCallingAssembly();
}));
}
}
}

I want to focus on the AssembliesFromApplicationBaseDirectory method since this is the one that caused me some head pain today. When AssembliesFromApplicationBaseDirectory gets invoked, the base directory of the current application domain is traversed, and any assembly found is added to the scanning operation. Note that I am also using WithDefaultConventions, which informs the scanner that any concrete class named Product , for example, implements an interface named IProduct , and it gets added to PluginType IProduct . This will spare you from using explicit declarations of PluginTypes for <IProduct>().Use<Product>() .

Because the application has multiple layers, the dependencies are quite intricate.  This is why I thought that if I used AssembliesFromApplicationBaseDirectory in the scanner configuration, it would be a great idea. Well, I was wrong, because I ended up with the following exception, which was thrown every time StructureMap was bootstrapping:

StructureMap configuration failures: Error: 170 Source: Registry: StructureMap.Configuration.DSL.Registry, StructureMap, Version=2.6.4.0, Culture=neutral, PublicKeyToken=e60ad81abae3c223 Unable to find the exported Type's in assembly System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. One or more of the assembly's dependencies may be missing. Could not load file or assembly 'System.Net.Http.Formatting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) System.IO.FileLoadException: Could not load file or assembly 'System.Net.Http.Formatting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. It was obvious that StructureMap was checking "all" assemblies from the base directory of current application domain. That is not what I intended to happen, there are system assemblies which are not needed in the dependency injection. I might say that I was lucky that this exception came to light, because this determined me to add some filtering into the process. If you check StructureMap documentation you will notice that AssembliesFromApplicationBaseDirectory has an overload which accepts a predicate, based on it, it will filter the assemblies which should be added to the scanning operation. So what I did is that I have defined a local array which holds the name of the assemblies which should be added to the scanning operation and used it in the filtering predicate.

It was obvious that StructureMap was checking "all" assemblies from the base directory of the current application domain. That is not what I intended.  There are system assemblies that are not needed in the dependency injection. I might say that I was lucky that this exception came to light, because this made me determined to add some filtering into the process. If you check StructureMap documentation, you will notice that AssembliesFromApplicationBaseDirectory has an overload that accepts a predicate.  Based on the predicate, it will filter the assemblies that should be added to the scanning operation. So what I did is I have defined a local array that holds the name of the assemblies that should be added to the scanning operation and used it in the filtering predicate.

namespace  Security.DependencyResolution
{
public class SecurityRegistry : Registry
{
public SecurityRegistry()
{
var assemblies = new[] { "Data.Repositories", " Security" };
Scan(config =>
{
config.AssembliesFromApplicationBaseDirectory(assembly => assemblies.Contains(assembly.FullName));
config.IncludeNamespace("Data.Repositories");
config.IncludeNamespace("Security");
});
} public static void Initialize(IContainer container)
{
container.Configure(ct => ct.Scan(scan =>
{
scan.LookForRegistries();
scan.TheCallingAssembly();
}));
}
}
}

Besides that, I decided to drop WithDefaultConventions in favor of an explicit declaration. At least this will make things more obvious, even though it is more verbose. The conclusion is... don't take shortcuts, not unless you are 100% sure it will work properly under any circumstances.

Published at DZone with permission of its author, Mihai Huluta .

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

StructureMap的更多相关文章

  1. StructureMap 代码分析之Widget 之Registry 分析 (1)

    说句实话,本人基本上没用过Structuremap,但是这次居然开始看源码了,不得不为自己点个赞.Structuremap有很多的类,其中有一个叫做Widget的概念.那么什么是Widget呢?要明白 ...

  2. ASP.NET 系列:单元测试之StructureMap

    ASP.NET使用StructureMap等依赖注入组件时最重要就是EntityFramework的DbContext对象要保证在每次HttpRequest只有一个DbContext实例,这里将使用第 ...

  3. StructureMap使用方法(转)

    终于到了题目中的MVC使用StructureMap依赖注入的配置与实现了.在ASP.Net三层架构应用中StructureMap的是最老的IOC/DI工具,也就是依赖注入,很多线上的项目都使用了Str ...

  4. StructureMap 学习笔记(1)

    前言 一个偶然的机会接触到了StructureMap,当时客户要求让程序具有较好的测试性,自然而然就想到了IOC 容器. 之后就去Google了一下, 不经意间在StackOverFlow找到一篇帖子 ...

  5. StructureMap Exception Code: 207 Internal exception while creating Instance '06fc8bd7-76db-47c1-8d71-31090a074f5e' of PluginType QIMS.Repository.IComStaffRepository. Check the inner exception for more

    标题翻译: StructureMap异常代码:207内部异常,同时创造PluginType QIMS.Repository.IComStaffRepository的实例“06fc8bd7-76db-4 ...

  6. Using StructureMap DI and Generic Repository

    In this post, i will show how to use generic repository and dependency injection using structuremap. ...

  7. StructureMap经典的IoC/DI容器

    StructureMap是一款很老的IoC/DI容器,从2004年.NET 1.1支持至今. 一个使用例子 //创建业务接口 public interface IDispatchService { } ...

  8. StructureMap依赖注入

    IOC:控制反转,是一种设计模式.一层含义是控制权的转移:由传统的在程序中控制依赖转移到由容器来控制:第二层是依赖注入:将相互依赖的对象分离,在spring配置文件中描述他们的依赖关系.他们的依赖关系 ...

  9. MVC使用StructureMap实现依赖注入Dependency Injection

    使用StructureMap也可以实现在MVC中的依赖注入,为此,我们不仅要使用StructureMap注册各种接口及其实现,还需要自定义控制器工厂,借助StructureMap来生成controll ...

随机推荐

  1. 配置zip版本的Tomcat启动

    1.配置jdk 2.CATALINA_HOME=c:\tomcat CATALINA_BASE=c:\tomcat 3.classpath=%CATALINA_HOME%\common\lib\ser ...

  2. 在Tomcat下指定Jsp生成的Java文件路径

    在tomcat的配置文件server.xml(路径:tomcat路径\conf下面)里,找到:<Context docBase="D:/workspace/icinfo/trunk/w ...

  3. 【Docker】常用命令

    1.查看正在运行的容器 [root@localhost ~]# docker ps CONTAINER ID        IMAGE               COMMAND            ...

  4. JSP常用跳转方式

      常用的跳转方式有以下几种: (1)href超链接标记,属于客户端跳转 (2)使用JavaScript完成,属于客户端跳转 (3)提交表单完成跳转,属于客户端跳转 (4)使用response对象,属 ...

  5. Windows 消息机制浅析

    1.       Windows 的历史 中国人喜欢以史为鉴,而事实也确实是,如果你能知道一件事情的来龙去脉,往往可以更容易地理解事物为什么会表现为当前这样的现状.所以,我的介绍性开场白通常会以一段历 ...

  6. Web Service——CXF

    1. 什么是CXF Apache CXF = Celtix + Xfire,开始叫 Apache CeltiXfire,后来更名为 Apache CXF 了,以下简称为 CXF.Apache CXF ...

  7. 【LeetCode】48. Rotate Image (2 solutions)

    Rotate Image You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees ...

  8. 数据源与JNDI资源实现JSP数据库连接池实例

    名词解释:JNDI的全称是java命名与目录接口(Java Naming and Directory Interface),是一个应用程序设计的API,为开发人员提供了查找和访问各种命名和目录服务的通 ...

  9. RHCE7 -- systemctl命令

    查询所有单元的状态: [root@rhce7 ~]# systemctl UNIT LOAD ACTIVE SUB DESCRIPTION proc-sys-fs-binfmt_misc.automo ...

  10. redis 学习札记4-sortset

    redis 学习笔记4--sortset redis学习笔记3--sortSet 终于到最后一个数据结构了,加油!! 整体结构图: http://dl.iteye.com/upload/picture ...