Autofac依赖性解析错误

时间:2013-07-02 16:34:08

标签: c#-4.0 inversion-of-control ioc-container autofac

我有一个班级

 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     {         private static 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());

所请求的服务&#39; IDbContext&#39;尚未注册。要避免此异常,请注册组件以提供服务,使用IsRegistered()检查服务注册,或使用ResolveOptional()方法解析可选依赖项。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

解决方案1。 您已将IDbContext注册为命名服务。

.Named<IDbContext>("Speed")

因此,您必须使用ResolveNamed方法。

_container.ResolveNamed<IDbContext>("Speed");

解决方案2。 您只需将IDbContext注册为类型即可。在这种情况下,Resolve()方法应该可以正常工作。

builder.Register<IDbContext>(c =>
          new DbContext(ConfigurationManager.ConnectionStrings["Speed"].ConnectionString))
          .InstancePerDependency();