Dependency injection 在不注册第一个的情况下解析类型-prism 4和Untiy
首先,我想说的是,我对棱镜、DI和容器的概念很陌生。我正在查看随Prism库提供的一个代码示例: 代码只是将带有“Hello World”字符串的视图(在TextBlock元素中)注入shell中的一个区域 当应用程序启动时,它将创建一个新的引导程序实例,该实例将创建并初始化shell:Dependency injection 在不注册第一个的情况下解析类型-prism 4和Untiy,dependency-injection,unity-container,prism,Dependency Injection,Unity Container,Prism,首先,我想说的是,我对棱镜、DI和容器的概念很陌生。我正在查看随Prism库提供的一个代码示例: 代码只是将带有“Hello World”字符串的视图(在TextBlock元素中)注入shell中的一个区域 当应用程序启动时,它将创建一个新的引导程序实例,该实例将创建并初始化shell: public class Bootstrapper : UnityBootstrapper { protected override DependencyObject CreateShell()
public class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<Shell>();
}
protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.RootVisual = (UIElement)this.Shell;
}
protected override void ConfigureModuleCatalog()
{
base.ConfigureModuleCatalog();
ModuleCatalog moduleCatalog = (ModuleCatalog)this.ModuleCatalog;
moduleCatalog.AddModule(typeof(HelloWorldModule.HelloWorldModule));
}
}
这对我来说就像一个魔术,所以我尝试创建我自己的类型(MyType),并以相同的方式解决它:
Container.Resolve<MyType>();
Container.Resolve();
通过在MyType构造函数中设置breakepoint,我看到它确实解析了MyType。有人能给我解释一下它是如何工作的吗?这两条线索应该能回答你的问题:
Damian您不需要注册要解析的类型。您需要注册要解析的类型的依赖项。在这种情况下,Shell不需要任何依赖项,因此您可以简单地解决它。但举个例子(不是真的),如果您的shell获得一个接口IService作为参数,那么您必须在解析shell之前注册IService 否则,您将获得依赖项解析失败异常。在Prism 4.1中,由于TryResolve,它将被默默吞下
Container.Resolve<MyType>();