StructureMap
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的更多相关文章
- StructureMap 代码分析之Widget 之Registry 分析 (1)
说句实话,本人基本上没用过Structuremap,但是这次居然开始看源码了,不得不为自己点个赞.Structuremap有很多的类,其中有一个叫做Widget的概念.那么什么是Widget呢?要明白 ...
- ASP.NET 系列:单元测试之StructureMap
ASP.NET使用StructureMap等依赖注入组件时最重要就是EntityFramework的DbContext对象要保证在每次HttpRequest只有一个DbContext实例,这里将使用第 ...
- StructureMap使用方法(转)
终于到了题目中的MVC使用StructureMap依赖注入的配置与实现了.在ASP.Net三层架构应用中StructureMap的是最老的IOC/DI工具,也就是依赖注入,很多线上的项目都使用了Str ...
- StructureMap 学习笔记(1)
前言 一个偶然的机会接触到了StructureMap,当时客户要求让程序具有较好的测试性,自然而然就想到了IOC 容器. 之后就去Google了一下, 不经意间在StackOverFlow找到一篇帖子 ...
- 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 ...
- Using StructureMap DI and Generic Repository
In this post, i will show how to use generic repository and dependency injection using structuremap. ...
- StructureMap经典的IoC/DI容器
StructureMap是一款很老的IoC/DI容器,从2004年.NET 1.1支持至今. 一个使用例子 //创建业务接口 public interface IDispatchService { } ...
- StructureMap依赖注入
IOC:控制反转,是一种设计模式.一层含义是控制权的转移:由传统的在程序中控制依赖转移到由容器来控制:第二层是依赖注入:将相互依赖的对象分离,在spring配置文件中描述他们的依赖关系.他们的依赖关系 ...
- MVC使用StructureMap实现依赖注入Dependency Injection
使用StructureMap也可以实现在MVC中的依赖注入,为此,我们不仅要使用StructureMap注册各种接口及其实现,还需要自定义控制器工厂,借助StructureMap来生成controll ...
随机推荐
- CSS3实现两行或三行文字,然后多出的部分省略号代替
概述 -webkit-line-clamp 是一个 不规范的属性(unsupported WebKit property),它没有出现在 CSS 规范草案中.限制在一个块元素显示的文本的行数. 为了实 ...
- Python之L.reverse()和L.sort()
# -*- coding: utf-8 -*- #python 27 #xiaodeng #Python之L.reverse()和L.sort() #http://python.jobbole.com ...
- js createElement appendChild createTextNode用法
xml不支持innerHTML 1 <p id="bj">北京</p> <script type="text/javascript" ...
- getsockopt和accept需要注意的两个细节
1,getsockopt连续调用问题 通常情况下,在一个socket fd上出现错误时,我们会通过 int status; socklen_t slen; getsockopt(fd, SOL_SOC ...
- IDEA的maven项目中静态文件编译的路径问题(未测试)
转自:http://www.cnblogs.com/signheart/p/6625126.html IDEA的maven项目中,默认源代码目录下的xml等资源文件并不会在编译的时候一块打包进clas ...
- mybatis实现多表联合查询
本文转自:http://www.cnblogs.com/xdp-gacl/p/4264440.html#!comments 一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) ...
- HDUOJ-----(1329)Calling Extraterrestrial Intelligence Again
Calling Extraterrestrial Intelligence Again Time Limit: 2000/1000 MS (Java/Others) Memory Limit: ...
- nyoj------擅长排列的小明
擅长排列的小明 时间限制:1000 ms | 内存限制:65535 KB 难度:4 描述 小明十分聪明,而且十分擅长排列计算.比如给小明一个数字5,他能立刻给出1-5按字典序 ...
- 也来学学插件式开发续-利用MEF
前面一个博客:也来学学插件式开发中很多朋友留言说可以用MEF来实现.于是我就试着用MEF实现了一下. 步骤和上一篇差不多,只是加载插件的方式有所不同.这只是一个自己的示例程序,肯定有很多不足之处,欢迎 ...
- Linux命令-实时监测命令:watch
watch 是一个非常实用的命令,基本所有的 Linux 发行版都带有这个小工具,如同名字一样,watch 可以帮你监测一个命令的运行结果,省得你一遍遍的手动运行..在Linux下,watch是周期性 ...