gpt4 book ai didi

c# - 如何在数据层使用 Caliburn.Micro SimpleContainer

转载 作者:太空宇宙 更新时间:2023-11-03 17:41:36 27 4
gpt4 key购买 nike

也许这是一个愚蠢的问题,但我坚持下去。

我试图在整个应用程序中使用 SimpleContainer 作为 IoC,所以在我的数据访问层中,我以这种方式定义了一个 Bootstrap :

    public class AppBootstrapper : BootstrapperBase 
{
SimpleContainer container;

public AppBootstrapper()
{
Start();
}

protected override void Configure()
{
container = new SimpleContainer();
container.PerRequest<IMyClass, MyClass>();
}

protected override object GetInstance(Type service, string key)
{
var instance = container.GetInstance(service, key);
if (instance != null)
return instance;

throw new InvalidOperationException("Could not locate any instances.");
}

但是我该如何使用它呢?

我只是想获得一个实现并尝试编写:
IMyClass mc = new IoC.GetInstance(IMyClass );

但我没有找到如何

我试过了:
SimpleContainer container = new SimpleContainer();
IMyClass mc = new container.GetInstance(IMyClass,null);

和:
IMyClass mc = new IoC.GetInstance(IMyClass, null);

但它们都不起作用。

怎么了?

编辑:

而且,如果我为每个项目都有一个 AppBootstrapper.cs 都运行良好或最佳实践不同?

最佳答案

IMyClass mc = new IoC.GetInstance(IMyClass );

你可以这样做,因为 IoCstatic类,所以你不能创建它的新实例,而是你可以这样做:
IMyClass mc = IoC.Get<IMyClass>();

然而,这也不是推荐的方式。

在你像这样初始化你的 Bootstrap 之后,假设你有一个 SellViewModel像这样:
public class ShellViewModel {

private IMyClass _mc;

public ShellViewModel(IMyClass mc) {
_mc = mc;
}
}

现在,当 Caliburn.Micro 尝试实例化 ShellViewModel它会注意到构造函数接受 IMyClass 的实例。 ,然后它将自动为您创建该类的实例并将其提供给 ShellViewModel .

我真的建议你阅读 Dependency Inversion , Inversion of Control ,然后阅读 SimpleContainer 的文档课,然后阅读文章 Screens, Conductors and Composition来感受一下整个过程。

关于c# - 如何在数据层使用 Caliburn.Micro SimpleContainer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19361834/

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