我有一堂课
public interface IDbContext : IDisposable
{
IDbConnection Connection { get; }
IDbTransaction CreateOpenedTransaction();
IEnumerable<T> ExecuteProcedure<T>(string procedure, dynamic param = null, IDbTransaction transaction = null);
int ExecuteProcedure(string procedure, dynamic param = null, IDbTransaction transaction = null);
}
这是实现:
public sealed class DbContext : IDbContext
{
private bool disposed;
private SqlConnection connection;
public DbContext(string connectionString)
{
connection = new SqlConnection(connectionString);
}
public IDbConnection Connection
{
get
{
if (disposed) throw new ObjectDisposedException(GetType().Name);
return connection;
}
}
public IDbTransaction CreateOpenedTransaction()
{
if (connection.State != ConnectionState.Open)
Connection.Open();
return Connection.BeginTransaction();
}
我尝试像这样使用 autofac 解决依赖关系:
公共类 RepositoryBaseTest { 私有静态 IContainer _container;
[TestInitialize]
public virtual void TestInitialize()
{
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(typeof(ICommandHandler<object>).Assembly)
.AsImplementedInterfaces()
.SingleInstance();
builder.RegisterAssemblyTypes(typeof(IQuery<object>).Assembly)
.AsImplementedInterfaces()
.SingleInstance();
builder.RegisterAssemblyTypes(typeof(IQueryMultiple<object>).Assembly)
.AsImplementedInterfaces()
.SingleInstance();
builder.Register<IMemberRepository>(c =>
new MemberRepository(
c.Resolve<IDbContext>()))
.SingleInstance();
builder.Register<IDbContext>(c =>
new DbContext(ConfigurationManager.ConnectionStrings["Speed"].ConnectionString))
.Named<IDbContext>("Speed")
.InstancePerDependency();
_container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
}
#region Resolve
protected void ExecuteCommand<T>(T command)
{
_container.Resolve<ICommandHandler<T>>().Execute(command);
}
protected IEnumerable<T> Query<T>(Func<T, bool> condition)
{
return _container.Resolve<IQueryMultiple<T>>().Where(condition);
}
protected T Select<T>(Func<T, bool> condition)
{
return _container.Resolve<IQuery<T>>().Select(condition);
}
protected T Resolve<T>()
{
return _container.Resolve<T>();
}
#endregion
}
在课堂测试中,我尝试测试:
public class MemberRepositoryTest : RepositoryBaseTest
{
private IMemberRepository _memberRepository;
[TestInitialize]
public override void TestInitialize()
{
base.TestInitialize();
_memberRepository = new MemberRepository(Resolve<IDbContext>());
}
但我在这条指令中发现了一个错误:_memberRepository = new MemberRepository(Resolve());
请求的服务“IDbContext”尚未注册。要避免此异常,请注册一个组件以提供服务,使用 IsRegistered() 检查服务注册,或使用 ResolveOptional() 方法解决可选依赖项。
我该如何解决这个问题?