我想将我的上下文包装在一个界面中,以便更容易使用RhinoMocks进行模拟。
//Instead of creating a concrete type I want to inject the interface
public Repository(ISessionService sessionService, IMyContext context)
{
//This gets the correct connection string dynamically based on a dropdown selection
var connectionString = CustomerConnection.GetCustomerConnection(sessionService.GetCustomerId());
//see link below
_context = new MyEntity(connectionString.ToEntityConnectionString(typeof(MyEntity)));
}
This converts an ADO.Net connection string to an EF connections string
这是自定义代码,用于扩展我从DB第一个模型获得的生成实体。它只允许我传递连接字符串而不是使用它 这是由设计师创造的。使用它的原因是我们使用我们所有表所基于的模型表。
public partial class MyEntity : IMyContext
{
public MyEntity(string connectionString) : base(connectionString){}
}
使用Ninject我认为它看起来像这样:
kernel.Bind<IMyContext>().To<MyEntity>().InRequestScope().WithConstructorArgument("connectionString", connectionString);
所以问题:
问题:我从会话中获得了customerId。国际奥委会只建立一次 问题:如何在下拉列表更改时更改上下文
问题:sessionService是它自己的实体 问题:IOC中的值是否可访问?
我是从错误的角度来解决这个问题吗?
答案 0 :(得分:0)
所以我对这种情况采取了不同的方法。我决定创建一个IEntityService,而不是注入IMyContext和ISessionService 我可以模拟然后存根返回我的上下文的方法:
public Repository(IEntityService entityService)
{
_context = entityService.GetCustomerContext();
}
public partial class MyEntity : IMyContext
{
public MyEntity(string connectionString) : base(connectionString){}
}
public class EntityService : IEntityService
{
private readonly ISessionService _sessionService;
public EntityService(ISessionService sessionService)
{
_sessionService = sessionService;
}
//This is only public because I need the connectionString to get a List of all the stored procs on the table.
public string GetConnectionString()
{
var connectionString = "";
CustomerConnection.GetCustomerConnection(_sessionService.GetCustomerId(), out connectionString);
return connectionString;
}
public ICustomerContext GetCustomerContext()
{
return new MyEntity(connectionString.ToEntityConnectionString(typeof(MyEntity)));
}
}
现在在我的测试中我只需要存根GetCustomerContext()方法的返回(我正在使用RhinoMocks和NUnit):
private Repository _sut;
private IEntityService _serviceFake;
private ICustomerContext _contextFake;
[SetUp]
public void SetUp()
{
_serviceFake = MockRepository.GenerateMock<IEntityService>();
_sut = new Repository(_serviceFake);
_contextFake = MockRepository.GenerateMock<ICustomerContext>();
_serviceFake.Stub(x => x.GetCustomerContext()).Return(_contextFake);
}
现在我可以测试各种方法来验证期望。