简体   繁体   English

使用简单注入器PerWebRequest注册通用接口和具体类的语法

[英]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. 我在PerWebRequest的基础上无法获得使用简单注入器注册通用接口及其具体实现的正确语法。

This is the line registering with Simple Injector's container in Global.asax that causes the error: 这是在Global.asax中向Simple Injector的容器注册的行,这会导致错误:

 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) 我收到错误消息:Visual Studio中的IntelliSense中Type Argument is Missing类型参数( container.RegisterPerWebRequestIUnitOfWork<>的第一个类型参数用红色下划线IUnitOfWork<>

What should the correct syntax be? 正确的语法应该是什么?

What you are getting is a C# compiler error; 您得到的是C#编译器错误; the C# compiler (and the CLR) don't accept open-generics in method arguments. C#编译器(和CLR)在方法参数中不接受开放泛型。

The RegisterPerWebRequest has been obsoleted in v3 (it's still there for backwards compatibility). RegisterPerWebRequest在v3中已作废(为了向后兼容,它仍然存在)。 The best way is to do this: 最好的方法是这样做:

container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

container.Register(typeof(IUnitOfWork<>), typeof(UnitOfWork<>), Lifestyle.Scoped);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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