I'am facing an issue with the architecture set in place while trying to use Autofac.
Error message encountered is the following:
None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'xx.xx.xxxxxxx.HomeController' can be invoked with the available services and parameters: Cannot resolve parameter 'xx.Service.Common.IGenericService
2[xx.Common.Models.EntCountry,System.Int32] countryService' of constructor 'Void .ctor(xx.Service.Common.IGenericService2[xx.Common.Models.EntCountry,System.Int32])'.
Repository Interface and Class
public interface IGenericRepository<T,TId>
where T: class , IEntity<TId>
{...}
public abstract class GenericRepository<T, TId> : IGenericRepository<T, TId>
where T : class, IEntity<TId>
where TId : class {}
Service Interface and Class
public interface IGenericService<T,TId> where T : class , IEntity<TId>
{...}
public abstract class GenericService<T, TId> : IGenericService<T, TId>
where T : class, IEntity<TId>
where TId : class{...}
Controller Code
public class HomeController : Controller
{
private readonly IGenericService<EntCountry, int> _countryService;
public HomeController(IGenericService<EntCountry, int> countryService)
{
_countryService = countryService;
}
// GET: Home
public ActionResult Index()
{
var countries = _countryService.GetAll();
return View();
}
}
My Autofac configuration for services and repository is the following:
builder.RegisterAssemblyTypes(Assembly.Load("XX.Data"))
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces()
.AsSelf()
.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies)
.InstancePerLifetimeScope();
builder.RegisterAssemblyTypes(Assembly.Load("XX.Service"))
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.AsSelf()
.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies)
.InstancePerLifetimeScope();
I tried to use the Register Generic method, but I still got the same error
builder.RegisterGeneric(typeof(GenericRepository<,>))
.As(typeof(IGenericRepository<,>))
.AsSelf()
.InstancePerDependency();
Thanks for your help.
best regards.
XX.Serviceassembly contains a concrete implementation ofGenericService- Cyril DurandGenericServiceis an abstract class. Autofac can instanciate an abstract class it needs a concrete class inheriting from it - Cyril Durand