简体   繁体   中英

How to register generic implementation of generic interface using Autofac?

I'm trying to register my repository using Autofac but I have a problem. Here's what I produced so far:

ContainerModule.cs

public class ContainerModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<XmlDataProvider>().As<IDataProvider>();
        builder.RegisterGeneric(typeof (TemplateRepository<,>)).As(typeof (IRepository<>)).SingleInstance();
    }

}

TemplateRepository{T}.cs

public class TemplateRepository<TTemplate, TEntity> : IRepository<TTemplate> where TTemplate : ITemplate
{
    public TemplateRepository(IDataProvider dataProvider)
    {
    }
}

[place when I'm trying resolve it]

 var markerRepository = container.Resolve<IRepository<MarkerTemplate>>();

Problem is, that Autofac doesn't even try construct my repository (I put there breakpoint and it's never hit). I'm receiving following exception:

An exception of type 'Autofac.Core.Registration.ComponentNotRegisteredException' occurred in Autofac.dll but was not handled in user code Additional information: The requested service '*********.Logic.Web.Repository.IRepository`1[[*********.Template.MarkerTemplate, *********.Logic.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

I tried to change my registration code to something more specific, but then, I'm receiving another exception saying, that TEntity isn't an open interface.

I tried several solutions found here, but none of these is working. Do you have any idea why I cannot register such case?

You have a generic implementation that has two generic type parameters and you register it as an interface with one generic type parameter. How do you think Autofac will figure out the second type parameter of your implementation generic (TEntity)?

I have this and it perfectly works:

public class RavenRepository<T> : IRepository<T> where T : Entity

...

builder.RegisterGeneric(typeof (RavenRepository<>))
    .AsSelf()
    .AsImplementedInterfaces()
    .InstancePerRequest();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM