如何在数据层中使用Caliburn.Micro SimpleContainer

gt.*_*ush 1 c# inversion-of-control caliburn.micro

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

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

    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.");
        }
Run Code Online (Sandbox Code Playgroud)

但是我怎么能用呢?

我只想获得一个实现并尝试编写:

IMyClass mc = new IoC.GetInstance(IMyClass );
Run Code Online (Sandbox Code Playgroud)

但我没有找到怎么样

我试过了:

SimpleContainer container = new SimpleContainer();
IMyClass mc = new container.GetInstance(IMyClass,null);
Run Code Online (Sandbox Code Playgroud)

和:

IMyClass mc = new IoC.GetInstance(IMyClass, null);
Run Code Online (Sandbox Code Playgroud)

但它们都不起作用.

怎么了?

编辑:

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

Ibr*_*jar 10

IMyClass mc = new IoC.GetInstance(IMyClass );
Run Code Online (Sandbox Code Playgroud)

你可以这样做,因为它IoC是一个static类,所以你不能创建它的新实例,而是你可以这样做:

IMyClass mc = IoC.Get<IMyClass>();
Run Code Online (Sandbox Code Playgroud)

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

在你初始化你的引导程序后,让我们说你有SellViewModel这样的:

public class ShellViewModel {

    private IMyClass _mc;

    public ShellViewModel(IMyClass mc) {
        _mc = mc;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我真的建议你阅读依赖倒置,控制反转,然后阅读SimpleContainer课程文档,然后阅读文章屏幕,指挥和组合,以了解整个过程.