我需要实现一组接口,在每个实现中,我需要访问调用上下文中可用的值,但不是接口方法的一部分。此外,调用上下文将实例作为依赖项接收。
为了解决这个问题,我想看看是否有某种方法可以创建一个类似于HttpContext的范围内容,但寿命有限。
这就是我设想的方式:OrderProcessor
类使userId
值可用于using
类实例的UserContext
范围内的所有方法调用。
问题是:这是否可能,如果是这样的话?
public class OrderProcessor
{
private readonly IBusiness _business;
public OrderProcessor(IBusiness business)
{
_business = business; // DI is providing us with an instance of MrBusiness
}
public static void ProcessOrders(string userId)
{
using (new UserContext(userId))
{
var thisUsersOrders = _business.GetOrders();
}
}
}
public interface IBusiness
{
List<Order> GetOrders();
}
public class MrBusiness : IBusiness
{
public List<Order> GetOrders()
{
var userId = UserContextManager.Current.UserId;
// Use the userId to retrieve data from somewhere
}
}
public class UserContextManager
{
public static UserContext Current
{
get
{
// If this had been a web application I could perhaps have used the Http context, hmm?
}
}
}
public class UserContext : IDisposable
{
public string UserId { get; }
public UserContext(string userId)
{
UserId = userId;
}
public void Dispose()
{
}
}