我刚开始从 Unity 迁移到 Autofac ,尝试注册实例时遇到问题.
I just started moving to Autofac from Unity and I have a problem when trying to register an instance.
public static void Register(ContainerBuilder containerBuilder, CancellationToken shutDownCancellationToken) { containerBuilder.RegisterType<CancellationToken>(); containerBuilder.RegisterInstance(shutDownCancellationToken); }我收到以下错误:
类型'CancellationToken'必须是引用类型,才能在通用类型或方法'RegistrationExtensions.RegisterInstance<T>(ContainerBuilder, T)'
The type 'CancellationToken' must be a reference type in order to use it as parameter 'T' in the generic type or method 'RegistrationExtensions.RegisterInstance<T>(ContainerBuilder, T)'
有人知道如何注册已经创建的结构实例吗?
Anyone knows how to register an already created struct instance?
推荐答案RegisterInstance方法作为class约束,不允许struct注册,但CancellationToken是struct,这就是为什么出现此错误的原因信息.要绕过此约束,可以使用Register方法注册您的实例.
The RegisterInstance method as a class constraint that disallow struct registration but CancellationToken is a struct this is why you have this error message. To bypass this constraint, you can register your instance using the Register method.
builder.Register(_ => source.Token).As<CancellationToken>();只要您的结构是不可变的,您将具有预期的行为,但是如果您使用可变结构,则该实例将不会被共享.就您而言,CancellationToken是不可变的,不会有任何怪异的副作用.
As long as your struct is immutable, you will have the expected behavior, but if you use a mutable struct, the instance won't be share. In your case, CancellationToken is immutable you won't have any weird side effect.
但是为什么RegisterInstance有class约束?
But why has RegisterInstance a class constraint ?
使用RegisterInstance方法注册实例时,预期的行为是每次注入对象时共享同一实例.
When you register an instance using the RegisterInstance method, the expected behavior is to share the same instance each time the object is injected.
根据定义,struct的作用类似于副本而不是引用.有关更多信息,请参见结构与类.
By definition a struct acts like a copy and not like a reference. See Struct vs Class for more information.
想象一下,您具有以下结构和使用该结构的服务:
Imagine you have the following struct and service using this struct :
public struct Foo { public Int32 A { get; set; } } public class Service { public Service(Foo foo) { this._foo = foo; } private Foo _foo; public void Set(Int32 a) { this._foo.A = a; } public void Print() { Console.WriteLine(this._foo.A); } }以及使用这些服务的以下代码:
and the following code using these service :
var builder = new ContainerBuilder(); Foo f = new Foo(); builder.Register(_ => f).As<Foo>(); builder.RegisterType<Service>(); IContainer container = builder.Build(); Service service1 = container.Resolve<Service>(); Service service2 = container.Resolve<Service>(); service1.Set(3); service1.Print(); service2.Print();即使仅注册Foo的一个实例,它也会显示3和0.我认为这就是RegisterInstance具有class约束的原因.
Even if you register only one instance of Foo it will display 3 and 0. I think this is the reason why RegisterInstance has a class constraint.
更多推荐
无法使用autofac注册结构实例
发布评论