解析时的Autofac和MVC4问题 - >请检查我的代码

时间:2013-11-16 06:22:02

标签: asp.net-mvc-4 generics repository autofac resolve

我正在使用Autofac和MVC4但不知怎的,当试图解决它失败时。注册期间我没有收到任何错误。代码如下所示:

    public void Register()
    {
        List<Assembly> assemblies = new List<Assembly>();
        assemblies.Add(Assembly.Load("KidsWear.DataLayer"));
        assemblies.Add(Assembly.Load("KidsWear.Repositories"));
        assemblies.Add(Assembly.Load("KidsWear.Contexts"));
        assemblies.Add(Assembly.Load("KidsWear.Entities"));
        assemblies.Add(Assembly.GetExecutingAssembly());

        var builder = new ContainerBuilder();
        builder.RegisterAssemblyTypes(assemblies.ToArray()).AsImplementedInterfaces();
        builder.RegisterControllers();
        //builder.RegisterControllers(Assembly.GetExecutingAssembly());
        var container = builder.Build();
        // test -> isRegistered  returns fals
        var isRegistered = container.IsRegistered(typeof(IProductRepository));
        // This line raises error: The requested service //KidsWear.Repositories.IProductRepository' has not been registered. 
        var concrete = container.Resolve<IProductRepository>();
        // End test
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }

我的所有接口都在“KidsWear.Repositories”中,实际的实现在“KidsWear.DataLayer”中,“KidsWear.Contexts”具有Generic存储库和Context。 ProductRepository接口如下所示:

public interface IProductRepository : IGenericRepository<Product>
{

}

产品存储库继承自GenericRepository和IProductRepository,如下所示:

public class ProductRepository : GenericRepository<Product>, IProductRepository
{
    public ProductRepository()
    {

    }

    //Todo: add any extra subs specific to Product
}

任何人都可以告诉我为什么这个注册不起作用以及这个错误是什么?只是在调试模式下,如果我将鼠标悬停在容器上,我可以看到它已被初始化。

非常感谢

1 个答案:

答案 0 :(得分:0)

这段确切的代码完美无缺。实际上并不确定问题是什么。不确定Visual Studio是否需要重启或者Autofac播放效果不佳!!!