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 ...
随机推荐
- 【CMS】DedeCMS Error: (PHP 5.3 and above) Please set 'request_order' ini value to include C,G and P (recommended: 'CGP') in php.ini
DedeCMS Error: (PHP 5.3 and above) Please set 'request_order' ini value to include C,G and P (recomm ...
- HTTP报文01
#xiaodeng #HTTP报文01 #HTTP权威指南 45 报文向下游流动- 不管是请求报文还是响应报文,所有报文都会向下游流动. 所有报文的发送者都在接收者的上游. 报文的组成部分 对报文进行 ...
- Tomcat自带log的配置详解
最近几天被日志搞得烦死了,不详细了解不行呀! Tomcat根目录文件作用说明 根目录下有bin,conf,lib,logs,temp,webapps,work 7个文件夹 bin目录 主要是用来存放t ...
- Linux下通用线程池的创建与使用
线程池:简单地说,线程池 就是预先创建好一批线程,方便.快速地处理收到的业务.比起传统的到来一个任务,即时创建一个线程来处理,节省了线程的创建和回收的开销,响应更快,效率更高. 在linux中,使用的 ...
- 【laravel5.4】重定向带参数
1. 2.重定向回上一页面 3.返回上一页面带参数
- dom 解析xml文件
JAXP技术 JAXP即Java Api for Xml Processing该API主要是SUN提供的用于解析XML数据的一整套解决方案,主要包含了DOM和SAX解析技术.大家可以参见SUN的以下两 ...
- mybatis启动报错Result Maps collection already contains value forxxx
ssm搭建过程中启动tomcat,报错: Cause: java.lang.IllegalArgumentException: Result Maps collection already conta ...
- ios NSURLSession使用说明及后台工作流程分析
NSURLSession是iOS7中新的网络接口,它与咱们熟悉的NSURLConnection是并列的.在程序在前台时,NSURLSession与NSURLConnection可以互为替代工作.注意, ...
- 【LeetCode】12. Integer to Roman (2 solutions)
Integer to Roman Given an integer, convert it to a roman numeral. Input is guaranteed to be within t ...
- RabbitMQ消息队列(四):分发到多Consumer(Publish/Subscribe)[转]
上篇文章中,我们把每个Message都是deliver(提供)到某个Consumer.在这篇文章中,我们将会将同一个Message deliver(提供)到多个Consumer中.这个模式也被成为 & ...