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 ...
随机推荐
- “error: command 'x86_64-linux-gnu-gcc' failed with exit status 1” in virtualenv
Most of the time these are dependency-issues. Following the stack-trace of the gcc compiler one ca ...
- uniq命令 (转)
uniq命令可以去除排序过的文件中的重复行,因此uniq经常和sort合用.也就是说,为了使uniq起作用,所有的重复行必须是相邻的. uniq语法 [root@www ~]# uniq [-icu] ...
- centos7 卸载 gitlab
标黑的就是关键命令,先停止gitlab服务,然后rpm -e卸载,然后查看剩余gitlab进程,然后杀死主进程,然后删除所有相关目录 1 [liuyx@MiWiFi-R3L-srv ~]$ sudo ...
- 腾讯云-搭建 WordPress 个人博客
搭建 WordPress 个人博客 准备 LNMP 环境 任务时间:30min ~ 60min LNMP 是 Linux.Nginx.MySQL 和 PHP 的缩写,是 WordPress 博客系统依 ...
- k8s内核参数调优
cat /etc/sysctl.conf kernel.core_uses_pid=1 kernel.pid_max=4194303 kernel.ctrl-alt-del=1 # kernel.co ...
- vs.net使用技巧
1.快捷键收缩和展开代码段 i. Ctrl-M-O 折叠所有方法 ii. Ctrl-M-P 展开所有方法并停止大纲显示(不可以再折叠了) iii. Ctrl-M-M 折叠或展开当前方法 i ...
- jquery api 常见 事件操作
change.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html ...
- LinkedHashMap插入无序且链式操作
Iterator<Entry<Integer, Integer>> ite=lhmap.entrySet().iterator(); ite.next(); ite.remov ...
- HDUOJ--4565 So Easy!
So Easy! Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Su ...
- java集合框架03——ArrayList和源码分析
最近忙着替公司招人好久没写了,荒废了不好意思. 上一章学习了Collection的架构,并阅读了部分源码,这一章开始,我们将对Collection的具体实现进行详细学习.首先学习List.而Array ...