C# 指定在 Castle Windsor 注册组件的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/925244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Specifying instance for registration of a component with Castle Windsor
提问by Niall Connaughton
I have what is probably a simple question here about Castle Windsor, which I haven't been using for very long. I'm trying to register a service with a specific instance that will be the singleton implementation of the service.
我有一个关于温莎城堡的可能是一个简单的问题,我已经很久没有使用了。我正在尝试使用特定实例注册服务,该实例将成为该服务的单例实现。
The container cannot try to create the implementation of the service itself because it has dependencies that the container will not be able to resolve. I have an instance of the service and I want that to be the one and only instance used for anyone requesting the service. But I appear to be having very little luck.
容器无法尝试创建服务本身的实现,因为它具有容器无法解析的依赖项。我有一个服务实例,我希望它成为任何请求服务的人使用的唯一实例。但我似乎运气不佳。
I momentarily had hopes raised by using this code:
我暂时对使用此代码产生了希望:
container.Register(Component.For<IMyInterface>().Instance(serviceObj));
But all Castle does with the instance is do a .GetType() on it and register the type. Requests for the service will subsequently cause the container to try to create that type and fail when it can't fill the dependencies.
但是 Castle 对实例所做的一切都是在其上执行 .GetType() 并注册类型。对服务的请求随后将导致容器尝试创建该类型并在无法填充依赖项时失败。
So is there any way to do what I want to do here? If not I will create some kind of IServiceProvider that fetch the instance of the service and have no dependencies for the container to fill out. But this feels like more of a work around than the right solution.
那么有什么办法可以在这里做我想做的事情吗?如果不是,我将创建某种 IServiceProvider 来获取服务的实例,并且没有容器需要填写的依赖项。但这感觉更像是一种解决方法,而不是正确的解决方案。
Any suggestions? Thanks!
有什么建议?谢谢!
采纳答案by Gerrie Schenck
Try using the AddComponentInstancemethod on the container's Kernel object. I think this is what you need.
尝试在容器的 Kernel 对象上使用AddComponentInstance方法。我认为这就是你所需要的。
Please note:This technique is now deprecated. Use container.Register(Component.For<T>().Instance(myT));
instead (thanks to eouw0o83hf)
请注意:此技术现已弃用。使用container.Register(Component.For<T>().Instance(myT));
替代(感谢eouw0o83hf)
回答by Bojan Resnik
You can do that through the Kernel
property of the container:
您可以通过Kernel
容器的属性来做到这一点:
container.Kernel.AddComponentInstance<IMyInterface>(serviceObj);