TinyIoC注册未知类型的实例(TinyIoC register instance of unknown type)

编程入门 行业动态 更新时间:2024-10-26 19:28:25
TinyIoC注册未知类型的实例(TinyIoC register instance of unknown type)

我试图允许我的库的用户通过tinyioc内部连接,传递他们自己在我的库中定义的接口的实现,然后在需要实例时将其解析。

例如,用户可以这样做:

public class Logger : Things.ILogger { // Implement members public void Log(string s) { ... } } var thing = new Things.ThingBuilder().WithLogger(new Logger()).Build();

在我的库中,我想连接传入的记录器。类似于:

namespace Things { public class ThingBuilder() { private ILogger logger; public ThingBuilder WithLogger(ILogger logger) { this.logger = logger; return this; } public Thing Build() { TinyIocContainer container = new TinyIocContainer(); container.Register(ILogger, logger); // I want this to be used // wherever an ILogger is needed ... } } }

但是,我找不到TinyIoc让我这样做的方法。 这支持吗? 我知道TinyIoc支持注册它知道的类型的实例,但是如果类型未知则不支持。

I'm trying to allow users of my library, which is internally wired up via tinyioc, to pass in their own implementation of an interface defined within my library which will then be resolved to whenever an instance is needed.

For example, the user can do this:

public class Logger : Things.ILogger { // Implement members public void Log(string s) { ... } } var thing = new Things.ThingBuilder().WithLogger(new Logger()).Build();

Within my library I want to wire up the logger which is passed in. Something like:

namespace Things { public class ThingBuilder() { private ILogger logger; public ThingBuilder WithLogger(ILogger logger) { this.logger = logger; return this; } public Thing Build() { TinyIocContainer container = new TinyIocContainer(); container.Register(ILogger, logger); // I want this to be used // wherever an ILogger is needed ... } } }

However, I can't find a way TinyIoc will let me do this. Is this supported? I know that TinyIoc supports registering instances of types it knows about, but not if the type is unknown.

最满意答案

最后,我通过手动将用户提供的ILogger实例传递到库代码库中所需的任何地方来解决这个问题。 这是令人满意的,因为我认为反思我最初的期望是不切实际的。

I worked around this in the end by manually passing the user-supplied instance of ILogger to wherever it was required in the library codebase. This is satisfactory as I think on reflection my initial expectations were unrealistic.

更多推荐

本文发布于:2023-07-26 03:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1270686.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   类型   TinyIoC   register   type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!