我正在使用ASP.NET Web API & Ninject进行REST服务,尽管我怀疑这可能是比我的IoC框架特有的任何更一般的IoC问题。我有多个对象需要访问用户实体的一个简单的缓存:Web API中的长期对象的依赖注入?
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从我的数据库中拉用户实体。该存储库需要以某种方式注入缓存中,或者使用工厂实例化。
诀窍是,我已经能够创建缓存的唯一方式,Ninject将注入它的依赖关系,并且b)可以在整个缓存中访问缓存,注射到需要访问它的对象:
kernel.Bind<TestContext>().ToSelf();
kernel.Bind<UserCache>().ToSelf().InSingletonScope();
...然后在控制器(例如):
[Inject]
public UserCache Cache { get; set; }
我的问题是,这是长期治疗的最佳方法需要注射的生物体?还是有更好的方法,我错过了?我不想让缓存(或任何其他类似的对象)直接访问Ninject内核。
这不起作用。任何这样的对象都必须完全线程安全。 – SLaks
实际上,这将是线程安全的。上面的代码只是我用来了解Ninject应该如何工作的临时项目的一些示例。 –