AutoFac和解析链中的对象

时间:2015-08-07 12:27:07

标签: c# asp.net-web-api dependency-injection autofac

使用WebAPI和我的Repos的接口,AutoFac似乎试图实例化我的UserRepoitory,但是当它试图创建实例时,它会停留在他们的构造函数上。 / p>

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on 
type 'Db.UserRepository' can be invoked with the available services 
and parameters: Cannot resolve parameter 'Db.DbContext context' of constructor 'Void .ctor(Db.DbContext)'.
    public class UserRepository : IUserRepository
    {
        DbContext db = null;

        public UserRepository(DbContext context)
        {
            db = context;
        } 
    }

    public class FindABriefContext : DbContext
    {
        public FindABriefContext() : base("FindABriefContext")
        {}
    }

我的DI代码没什么特别的..

public static void RegisterContainer()
        {
            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(typeof(UserController).Assembly);

            //var asm = typeof(IUserRepository).Assembly;
            builder.RegisterAssemblyTypes(typeof(UserRepository).Assembly)
                .Where(x => x.Name.EndsWith("Repository")).AsImplementedInterfaces();

            var container = builder.Build();
            GlobalConfiguration.Configuration.DependencyResolver= new AutofacWebApiDependencyResolver(container);

        }

2 个答案:

答案 0 :(得分:1)

为了使容器实例化Repository,它需要满足它对DBContext的依赖。这就是为什么你需要告诉Autofac如何解决DbContext。

只需添加以下行

即可
builder.RegisterType<FindABriefContext>().As<DbContext>();

var container = builder.Builder();

答案 1 :(得分:0)

您需要将上下文作为参数传递到存储库中。

来自autofac文档:

{!! Form::text('fname', Auth::user()->fname, array('id'=>'fname', 'class'=>'form-control', 'type'=>'text')) !!}

或者我会使用工厂并注入工厂而不是注入所有存储库。

builder.RegisterType<ConfigReader>()
       .As<IConfigReader>()
       .WithParameter(new TypedParameter(typeof(string), "sectionName"));

然后你会注入单个工厂。

public class RepositoryFactory : IRepositoryFactory
{
        public IRepository<T> CreateRepository<T>() where T : class
        {
            var yourContext = new SomeContext(); //can also be injected
            return new Repository<T>(yourContext);
        }
}