Autofac and ASP .Net MVC 4 Web API

北战南征 提交于 2019-12-01 16:22:00

You have registered your IRepository wrong. With the line:

builder.RegisterType<SharePointRepository<IEntity>>().As<IRepository<IEntity>>();

You told Autofac that whenever somebody will request an IRepository<IEntity> give them a SharePointRepository<IEntity>, but you are requesting a concrete IRepository<Integration> so you get an exception.

What you need is the open generic registration feature of Autofac. So change your registration to:

builder.RegisterGeneric(typeof(SharePointRepository<>))
       .As(typeof(IRepository<>));

It will work as you would expect you when you ask for a IRepository<Integration> it will give a SharePointRepository<Integration>.

You also have a second unrelated problem: your SharePointRepository has only an internal constructor.

Autofac by default only looks for public constructors so you either change your constructor and class to public or you need to tell to Autofac to look for NonPublic constructors with the FindConstructorsWith method:

builder
    .RegisterType<SharePointRepository<IEntity>>()
    .FindConstructorsWith(
       new DefaultConstructorFinder(type => 
          type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance))) 
    .As<IRepository<IEntity>>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!