gpt4 book ai didi

c# - Autofac 约束绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 18:32:53 27 4
gpt4 key购买 nike

我正在考虑从 Ninject 转移到 Autofac,但正在努力转换其中一个有用的功能 - 通过属性进行约束绑定(bind)。

我目前有这个接口(interface)和实现:

public interface IRepository
{
IEnumerable<SomeObject> Get();
}

public class DBRepository : IRepository
{
public IEnumerable<SomeObject> Get()
{
// call the database
}
}

我有一个缓存实现,它将检查缓存,如果没有找到,调用数据库存储库。这被传递到构造函数中:

[DataNeeded]
public class CacheRepository : IRepository
{
private readonly IRepository dataRepo;

public CacheRepository(IRepository dataRepo)
{
this.dataRepo = dataRepo;
}

public IEnumerable<SomeObject> Get()
{
// check the cache and if nothing found:
return this.dataRepo.Get();
}
}

最后,我有一个将使用缓存获取对象的调用 Controller :

[CacheNeeded]
public class HomeController : ApiController
{
private readonly IRepository cacheRepo;

public CacheRepository(IRepository cacheRepo)
{
this.cacheRepo= cacheRepo;
}

public IEnumerable<SomeObject> Get()
{
return this.cacheRepo.Get();
}
}

正如您所看到的,我已经重新使用接口(interface)在数据存储库上添加了一个缓存层,并且这种模式非常有效。然后我使用了一些自定义属性来告诉 Ninject 我需要某种类型的 IRepository。配置如下:

kernel.Bind<IRepository>().To<DbRepository>().WhenClassHas<DataNeeded>();
kernel.Bind<IRepository>().To<CacheRepository>().WhenClassHas<CacheNeeded>();

有没有办法在 Autofac 中模仿这种行为?

最佳答案

我想不出用 Autofac 可以简洁明了地实现这种机制,但也许您可以使用 Autofac 的 meanings of selecting implementation 之一。 .我会使用键控服务,在你的情况下它看起来像这样:首先,你需要定义一个枚举而不是自定义属性

enum RepositoryKind {CacheNeeded, DataNeeded}

然后注册组件,用提供缓存或数据功能的组件标记它们,例如:

  builder.RegisterType<DbRepository>()
.Keyed<IRepository>(RepositoryKind.CacheNeeded);

builder.Register(c => new CacheRepository(c.ResolveKeyed<IRepository(RepositoryKind.CacheNeeded)))
.Keyed<IRepository>(RepositoryKind.DataNeeded);

builder.Register(c => new HomeController(c.ResolveKeyed<IRepository>(RepositoryKind.DataNeeded)));

这种方法的优点是您不会在 Controller 中透露您的实现细节并在配置中应用缓存。

关于c# - Autofac 约束绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18175169/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com