使用 Autofac 注册部分封闭的泛型类型

编程入门 行业动态 更新时间:2024-10-26 07:39:22
本文介绍了使用 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 你在 typeof 中指定了 T 但没有指定 O) ,试试:

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 通用约束将负责第一个参数应该是 Repository

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

但是它不适用于RegisterGeneric,因为它需要一个通用接口,所以需要创建一个IUnitOfWork...

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 构造函数中获得一个 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

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

发布评论

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

>www.elefans.com

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