简体   繁体   English

如何在简单注入器中将空值传递给构造函数?

[英]how to pass null value in to constructor in simple injector?

I have a service layer which is used by two applications a web application and window service. 我有一个服务层,供Web应用程序和窗口服务这两个应用程序使用。 I am using simple injector for both application. 我正在为这两种应用程序使用简单的注射器。

Window service does not requires all constructor parameters which are required in web application.So I need to pass null value for those constructor parameters.But Simple Injector does not allows me to pass null values. 窗口服务不需要Web应用程序中需要的所有构造函数参数,因此我需要为这些构造函数参数传递null值,但是Simple Injector不允许我传递null值。

I am registering the type for null values like this 我正在为这样的空值注册类型

container.Register<IDataProtectionProvider>(() => null);

but it give me error 但这给我错误

The registered delegate for type IDataProtectionProvider returned null. IDataProtectionProvider类型的已注册委托返回null。

Any help 任何帮助

Simple Injector does not allow passing null values into constructors, because constructors are for required dependencies. Simple Injector不允许将null值传递给构造函数,因为构造函数用于必需的依赖项。

Instead of passing null in, you should pass in a Null Object : 除了传递null之外,您应该传递Null对象

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral ("null") behavior. 在面向对象的计算机编程中,空对象是没有引用值或具有定义的中性(“空”)行为的对象。 The null object design pattern describes the uses of such objects and their behavior (or lack thereof). 空对象设计模式描述了此类对象的用途及其行为(或缺少行为)。 It was first published in the Pattern Languages of Program Design book series. 它最初在程序设计的模式语言丛书中出版。

Example: 例:

container.RegisterSingleton<IDataProtectionProvider>(new NullDataProtectionProvider());

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

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