我正在使用 ASP.NET Web API 和 Ninject 组合一个 REST 服务,尽管我怀疑这可能是一个比任何特定于我的 IoC 框架的更普遍的 IoC 问题。我有许多对象需要访问用户实体的简单缓存:
public class UserCache
{
private IList<User> users;
private IUserRepositoryFactory factory;
[Inject]
public UserCache(IUserRepositoryFactory factory)
{
this.factory = factory;
this.users = new List<User>();
}
public void Add(int id)
{
IUserRepository repo = factory.Create(new TestContext());
this.users.Add(repo.Get(id));
}
public int Count { get { return this.users.Count; } }
}
实际上,缓存是通读的,并且会使用 UserRepository(和关联的 IUserRepository 接口)填充用户实体:
public class UserRepository : IUserRepository
{
private readonly TestContext context;
public UserRepository(TestContext context)
{
this.context = context;
}
public User Get(int id)
{
return new User() { Name = "Test User" };
}
}
缓存是长期存在的,并在整个应用程序中共享。我的问题是:我想使用我的 UserRepository 从我的数据库中提取用户实体。这个存储库需要以某种方式注入缓存,或者使用工厂实例化。
The trick is, the only way I've been able to both a) create the cache such that Ninject will inject its dependencies and b) have access to the cache throughout the same is to bind the cache in singleton scope and inject it into objects that need access to it:
kernel.Bind<TestContext>().ToSelf();
kernel.Bind<UserCache>().ToSelf().InSingletonScope();
...and then in a controller (for example):
[Inject]
public UserCache Cache { get; set; }
My question is, is this the best way to treat long-lived objects that require injection? Or is there some better way that I'm missing? I don't want to give the cache (or any other objects like it) direct access to the Ninject kernel.