向Autofac注册部分封闭的泛型类型

编程入门 行业动态 更新时间:2024-10-26 09:28:57
本文介绍了向Autofac注册部分封闭的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有UnitofWork类,它实现了IUnitOfWork.我尝试在Autofac上注册:

I have UnitofWork class and it implement IUnitOfWork. I try to register that with Autofac:

var builder = new ContainerBuilder(); builder .RegisterGeneric(typeof(UnitOfWork<Repository<>,>)) .As(typeof(IUnitOfWork)) .InstancePerDependency();

实施是:

public class UnitOfWork<T, O> : IUnitOfWork where T : Repository<O> where O : BaseEntity { } public interface IUnitOfWork : IDisposable { void SaveChanges(); }

给出错误预期类型"

但是这个可以在另一个项目上工作

but this one work on another project:

public class Repository<T> : GenericRepository<T> where T : BaseEntity { public Repository(IDbContext context) : base(context) { } } public abstract class GenericRepository<T> : IRepository<T>, IQueryable<T> where T : BaseEntity { } builder .RegisterGeneric(typeof(Repository<>)) .As(typeof(IRepository<>)) .InstancePerHttpRequest();

推荐答案

您不能部分打开课程(例如,对于UnitOfWork<Repository<>,>,您已指定T,但未指定O)在typeof 内,尝试使用:

You cannot have partially opened classes (e.g. with UnitOfWork<Repository<>,> you have specified T but not O) inside a typeof, try it with:

var builder = new ContainerBuilder(); builder .RegisterGeneric(typeof(UnitOfWork<,>)) .As(typeof(IUnitOfWork)) .InstancePerDependency();

where T : Repository<O>通用约束将确保第一个参数应为Repository<>

The where T : Repository<O> generic constraint will take care of that the first argument should be an Repository<>

但是它不适用于RegisterGeneric,因为它需要通用接口,因此需要创建IUnitOfWork<T,O>…

But it won't work with RegisterGeneric because it requires a generic interface so need to create a IUnitOfWork<T,O>…

但是您的模型非常奇怪.为什么您的UnitOfWork需要一个Repository<>类型的自变量?

But your model is very strange. Why does your UnitOfWork need a Repository<> type argument?

除了将其作为类型参数之外,您还可以在UnitOfWork<E>构造函数中获得一个Repository<>:

Instead of having it as a type argument you can get an Repository<> in your UnitOfWork<E> constructor:

public class UnitOfWork<E> : IUnitOfWork<E> where E : BaseEntity { private readonly Repository<E> repository; public UnitOfWork(Repository<E> repository) { this.repository = repository; } //.. other methods }

IUnitOfWork<E>

public interface IUnitOfWork<E> : IDisposable where E : BaseEntity { void SaveChanges(); }

以及Autofac注册:

And the Autofac registration:

var builder = new ContainerBuilder(); builder .RegisterGeneric(typeof(Repository<>)).AsSelf(); builder .RegisterGeneric(typeof(UnitOfWork<>)) .As(typeof(IUnitOfWork<>)) .InstancePerDependency(); var container = builder.Build(); // sample usage var u = container.Resolve<IUnitOfWork<MyEntity>>();

更多推荐

向Autofac注册部分封闭的泛型类型

本文发布于:2023-11-04 12:28:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557940.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   Autofac

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!