Autofac: register generic type with unrelated interface

I am trying to register (as an instance for the request) a generic type and not a generic interface. I found many opposite examples on the Internet, but not for this.

So I have a class like this:

public class UnitOfWork<TContext> : IUnitOfWork where TContext : DbContext, new()

A common class, but not a common interface. In Autofac, I tried to register like this:

builder.RegisterGeneric(typeof(UnitOfWork<>)).As<IUnitOfWork>().InstancePerHttpRequest();

But I get an error: The "Namespace.UoW.IUnitOfWork" service is not an open description of a general type.

Of course, because it is not. But I do not know how to register it.

Thank.

+4
source share
1 answer

You only need it RegisterGenericif you also have a common interface.

IUnitOfWork, DbContext, UnitOfWork<Context> :

builder.RegisterType<UnitOfWork<Context>>()
       .As<IUnitOfWork>().InstancePβ€Œβ€‹erHttpβ€Œβ€‹Request();

, , IUnitOfWork, UnitOfWork<Context>.

+4

Source: https://habr.com/ru/post/1532013/


All Articles