Search code examples
c#.netsimple-injector

Syntax for Registering Generic Interface and Concrete Class with Simple Injector PerWebRequest


I am having trouble getting the correct syntax for registering a generic interface and its concrete implementation with Simple Injector on a PerWebRequest basis.

This is the line registering with Simple Injector's container in Global.asax that causes the error:

 container.RegisterPerWebRequest<IUnitOfWork<>, UnitOfWork<>>();

For completeness, these are the interface and concrete class definitions:

public class UnitOfWork<TContext> : IUnitOfWork<TContext>
    where TContext : IContext {

     public UnitOfWork(TContext context) {

     }
}

public interface IUnitOfWork<TContext> where TContext : IContext
{
    TContext Context { get; }
}

I am getting the error : Type Argument is Missing from IntelliSense in Visual Studio (the first type parameter on container.RegisterPerWebRequest : IUnitOfWork<> is underlined in red)

What should the correct syntax be?


Solution

  • What you are getting is a C# compiler error; the C# compiler (and the CLR) don't accept open-generics in method arguments.

    The RegisterPerWebRequest has been obsoleted in v3 (it's still there for backwards compatibility). The best way is to do this:

    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
    
    container.Register(typeof(IUnitOfWork<>), typeof(UnitOfWork<>), Lifestyle.Scoped);