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 ...
随机推荐
- gzip和zipfile模块
# -*- coding: utf-8 -*- #python 27 #xiaodeng #gzip和zipfile模块 #http://www.open-open.com/lib/view/open ...
- 创建安全的基于HTTP的api应用接口
#http://my.oschina.net/xiangtao/blog/196211 #要创建安全的基于HTTP的api接口,最重要的是要在服务端的进行请求的认证. #如何进行有效的服务端验证呢? ...
- 訪问可能没有定义的data (通过static类型flash.net:FileReference引用)
今天使用Flex实现了图片预览及其上传的功能,在整个开发过程中遇到了"訪问可能没有定义的data (通过static类型flash.net:FileReference引用)"错误, ...
- MyEclipse上的第一个java web
简单解说怎样MyEclipse上开发一个web project 以及怎样部署的问题. 第一步: 创建一个web project File -> New -> Web Project 将出现 ...
- 使用 Feed43
1.打开 Feed43 2.将标题.链接,时间等变化的字段删去用 {%} 代替.将固定且多余的字段删去用 {*} 代替.注意,源码中有换行的地方均需要添加{*} . 3.活学活用
- Nginx中Laravel的配置
server { listen 80; server_name sub.domain.com; set $root_path '/var/www/html/application_name/publi ...
- PHP-FastCGI详解
一.什么是 FastCGI FastCGI是一个可伸缩地.高速地在HTTP server和动态脚本语言间通信的接口.多数流行的HTTP server都支持FastCGI,包括Apache.Nginx和 ...
- navicat for mysql怎么注册?navicat11全系列破解教程(附注册码)
来自脚本之家 http://www.jb51.net/softjc/473494.html
- struts2的DevMode(开发模式)模式
本文转自:http://blog.csdn.net/q1054261752/article/details/48687119 在实际应用开发或者是产品部署的时候,对应着两种模式: ① 开发模式(dev ...
- HDUOJ---Can you solve this equation?
Can you solve this equation? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K ( ...