我是IoC的新手,我正在尝试使用StructureMap,但当我尝试获取对象实例时,它会抛出NullReferenceException。以下是我的初始化代码:
ObjectFactory.Initialize(x =>
{
x.ForRequestedType<IRepository<Customer>>().TheDefaultIsConcreteType<EFRepository<Customer>>();
x.ForRequestedType<ICustomerManager>().TheDefaultIsConcreteType<CustomerManager>();
});ICustomerManager使用ctor注入并接收IRepository:
public class CustomerManager : ICustomerManager
{
IRepository<Customer> _repository;
public CustomerManager(IRepository<Customer> repository)
{
_repository = repository;
}
public Customer GetCustomerById(int id)
{
return _repository
.With(c => c.PhoneNumbers)
.FirstOrDefault<Customer>(c => c.Id == id);
}
public IEnumerable<Customer> GetCustomersByName(string lastName, string firstName, string middleName)
{
return _repository.Query(new CustomerMatchesName(lastName, firstName, middleName));
}
}然后在我的服务层代码中,这一行抛出异常:
var manager = ObjectFactory.GetInstance<ICustomerManager>();我真的不知道从哪里开始调试,因为我对这些概念还很陌生。在这样一个简单的场景中,有什么可能出错的想法吗?
发布于 2011-06-10 00:42:56
您很可能会得到StructureMap无法构建对象的异常,这会导致空引用的级联异常,该异常已经吞噬了真正的异常。
调试这些场景的最佳解决方案是打开“捕获所有异常”、“Ctrl+Alt+E”和“标记”来捕获所有抛出的异常。
下一个要转到的工具是StructureMap,它提供了一个实用方法ObjectFactory.WhatDoIHave();
在我的所有项目中,我在Application_Start (我只做asp.net)的初始化代码中有以下代码块
#if DEBUG
string path = Server.MapPath("~/myproj.WhatDoIHave.txt");
string whatDoIHave = ObjectFactory.WhatDoIHave();
File.WriteAllText(path, whatDoIHave);
#endif这个输出给我提供了无数次的帮助。学习阅读此文件将使您基本上解决任何注册问题,因为您将能够确切地看到您做了什么,没有什么。
大多数情况下,使用StructureMap时,您最终会解决您所没有的问题。这通常归结为需要注册StructureMap不能满足的复杂类型。
https://stackoverflow.com/questions/6296238
复制相似问题