我有一个带有generichandler的应用程序,并希望使用 unity 注入依赖项。无论我尝试什么,我都会发现错误:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean
我试图在http://geekswithblogs.net/rhames/archive/2012/09/11/loosely-coupled-.net-cache-provider-using-depertiny-indoction.aspx.aspx.aspx.pection.pection.aspx.pection.pection.pection.aspx.pection.pection.pection.aspx.pection.pection.aspx.pection.pection.aspx.pection.pection.pection.aspx.pection.P>
我的处理程序的构造函数如下:
public class GetPerson : IHttpHandler
{
private IPersonRepository repo;
public GetPerson(IPersonRepository repo)
{
this.repo = repo;
}
ipsonrepository由cachedpersonrepositor实现。cachedpersonrepository包装了人格序列(如果在缓存中找不到项目,则用于数据访问)。 cachedpersonrepository和personRepository is ipsersonrepository :
public class CachedPersonRepository : IPersonRepository
{
private ICacheProvider<Person> cacheProvider;
private IPersonRepository personRepository;
public CachedPersonRepository(IPersonRepository personRepository, ICacheProvider<Person> cacheProvider)
{
此ipSersonrepository reperrepository是无参数的。
ICacheProvider<Person> is implemented by MemcachedCacheProvider<T>:
public class MemcachedCacheProvider<T> : ICacheProvider<T>
{
public T Get(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan relativeExpiry)
{
我尝试不成功以初始化我的global.asax文件application_start中的unity容器。DI对我来说是新手,我非常感谢关于我出错的任何建议。
实际上有两个问题。
首先,cachedpersonrepository使用了我以前没有正确理解的装饰器图案。一旦我理解了这一点
public static void Configure(IUnityContainer container)
{
container.RegisterType<ICacheProvider<Person>, MemcachedCacheProvider<Person>>();
container.RegisterType<IPersonRepository, PersonRepository>("PersonRepository", new ContainerControlledLifetimeManager());
container.RegisterType<IPersonRepository, CachedPersonRepository>(
new InjectionConstructor(
new ResolvedParameter<IPersonRepository>("PersonRepository"),
new ResolvedParameter<ICacheProvider<Person>>()));
container.Resolve<IPersonRepository>();
}
修复了此问题后,我仍然看到了相同的"无参数的构造函数为此对象定义"错误。
原因是我正在与iHttphandler合作,并且不可能在构造函数中注入依赖项。
我通过使用财产注入来解决此问题:
已将具有依赖关系属性的存储库添加到GetPerson处理程序中:
public class GetPerson : HandlerBase
{
[Dependency]
public IPersonRepository Repository { get; set; }
需要一个新的HTTP模块来检查实现我的处理程序的处理程序的请求:
public class UnityHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
}
public void Dispose() { }
private void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
IHttpHandler currentHandler = HttpContext.Current.Handler as HandlerBase;
if (currentHandler != null)
{
HttpContext.Current.Application.GetContainer().BuildUp(
currentHandler.GetType(), currentHandler);
}
}
}
资源:
http://download.microsoft.com/download/4/d/b/4dbc771d-9e24-4211-adc5-65812115e52e52d/depperityendendiondoctionwithunity.pdf(第4章,第4章,第60-63页),第60-63页
http://msdn.microsoft.com/en-us/library/ff664534(v = pandp.50).aspx