gpt4 book ai didi

c# - 依赖注入(inject)——通过配置文件在运行时选择DLL和类实现

转载 作者:太空宇宙 更新时间:2023-11-03 11:35:40 25 4
gpt4 key购买 nike

我有一个 API DLL(例如 API.dll),除了许多其他想法之外,它还提供了一个抽象类(< em>抽象类)。

现在利用那个 AbstractClass 我已经在两个不同的 dll 上实现了它:

  • First.API.Implementation.dllConcreteImplementation1
  • Second.API.Implementation.dllConcreteImplementation2

ConcreteImplementation1 和 ConcreteImplementation2 都是同一个抽象类的实现。

我想要的是一个应用程序,我可以在其中选择使用这两个 dll 中的哪一个,并通过它选择要使用的实现,而无需用户更改代码中的任何内容,并且如果可能的话,无需停止应用程序。

一些配置文件,我可以让应用程序使用我想要的任何实现。像这样的东西:

<appconfiguration>
<implementation_to_use>
<dll>First.API.Implementation.dll</dll>
<class>ConcreteImplementation1</class>
</implementation_to_use>
</appconfiguration>

我对依赖注入(inject)几乎一无所知,除了它的概念,但我想这非常适合这项任务。

我研究了几个 DI/IoC 库,但我并不熟悉所有的概念和名称。我可以使用任何我想要的库。据我所知,这些是最常用的:StructureMap , NinjectSprint.NET

此外,除了所有的 dll 和实现之外,我还需要指明该应用程序要使用的文件。我可以在同一个文件中指明它的路径吗?

我只需要一些提示和指导来实现这样的事情。使用其中一个库的一些示例会很棒。

谢谢。

最佳答案

让您开始使用 StructureMap ,创建一个控制台应用程序,在其中包含:

结构图.config:

<?xml version="1.0" encoding="utf-8" ?>
<StructureMap MementoStyle="Attribute">
<DefaultInstance
PluginType="DemoIoC.AbstractBase,DemoIoC"
PluggedType="DemoIoC.ConcreteImplementation1,DemoIoC"
Scope="Singleton" />
</StructureMap>

PluginType 和 PluggedType 属性是“FullyQualifiedClassName,AssemblyName”默认情况下,它将在可执行文件夹中查找程序集,我不确定您将如何为程序集指定另一个位置

范围有很多选项,例如单例、 transient 等

程序.cs:

namespace DemoIoC
{
using System;
using StructureMap;

public static class Program
{
public static void Main(string[] args)
{
// here you initialize structuremap from the config file.
// You could probably use a FileSystemWatcher to reinitialize
// whenever the structuremap.config file changes
ObjectFactory.Initialize(x =>
{
x.UseDefaultStructureMapConfigFile = true;
});

var concrete = ObjectFactory.GetInstance<AbstractBase>();

concrete.Method1();

Console.ReadKey(true);
}
}
}

抽象库.cs:

namespace DemoIoC
{
public abstract class AbstractBase
{
public abstract void Method1();
}
}

ConcreteImplementation1.cs:

namespace DemoIoC
{
using System;

public class ConcreteImplementation1 : AbstractBase
{
public override void Method1()
{
Console.WriteLine("Called ConcreteImplementation1");
}
}
}

关于c# - 依赖注入(inject)——通过配置文件在运行时选择DLL和类实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6365539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com