Jos*_*ins 1 c# asp.net-mvc ninject asp.net-web-api
我正在使用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; } }
}
Run Code Online (Sandbox Code Playgroud)
在实践中,缓存是直读的,并且将使用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" };
}
}
Run Code Online (Sandbox Code Playgroud)
缓存是长期存在的,并在整个应用程序中共享.我的问题是:我想使用我的UserRepository从我的数据库中提取用户实体.需要以某种方式将此存储库注入缓存,或使用工厂进行实例化.
诀窍是,我能够同时创建缓存的唯一方法是使Ninject注入其依赖项并且b)在整个缓存中访问缓存是将缓存绑定在单一范围内并将其注入对象需要访问它:
kernel.Bind<TestContext>().ToSelf();
kernel.Bind<UserCache>().ToSelf().InSingletonScope();
Run Code Online (Sandbox Code Playgroud)
...然后在控制器中(例如):
[Inject]
public UserCache Cache { get; set; }
Run Code Online (Sandbox Code Playgroud)
我的问题是,这是治疗需要注射的长寿命物体的最佳方法吗?还是有一些我错过的更好的方法?我不想让缓存(或类似的任何其他对象)直接访问Ninject内核.
这不应该是另一种方式吗?你应该在你的控制器中使用IUserRepository,并且如果它已经被缓存,则应该从缓存中获取数据(如果使用拦截器完成,则更好),否则应该访问数据库.
这样您就不必担心长寿的缓存对象的生命周期.请记住,在一天结束时,整个WebAPI(到目前为止)在Web堆栈上运行,这意味着可以根据不同因素意外地回收应用程序.
| 归档时间: |
|
| 查看次数: |
573 次 |
| 最近记录: |