您好我尝试使用Windosor Castle和Caliburn Micro。到目前为止,我只使用MEF。
我找到了这位Castle Boostraper:https://gist.github.com/1127914
我将此调用添加到我的项目并修改了App.xaml文件:
<Application x:Class="Chroma_Configer.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Bootstraper="clr-namespace:Chroma_Configer.Bootstraper">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<Bootstraper:CastleBootstrapper x:Key="bootstrapper" />
<Style x:Key="MainView_FontBaseStyle" TargetType="{x:Type Control}">
<Setter Property="FontFamily" Value="Arial"/>
</Style>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
我创建ShellView(WPF)和ShellViewModel:
public interface IShellViewModel
{
}
public class ShellViewModel : Conductor<IScreen>.Collection.OneActive,
IShellViewModel
{
}
当我跑步时,我收到此错误:
{"No component for supporting the service Chroma_Configer.ViewModels.IShellViewModel was found"}
我在温莎城堡开始我知道他的工作是这样的:
var container = new WindsorContainer();
container.AddComponent("JsonUtil", typeof(IShellViewModel), typeof(ShellViewModel));
var shell = container.Resolve<IShellViewModel>();
在MEF我用户属性 [导出] 和 [导入]。我可以帮助我解决这个问题吗?
另一个问题是我有一些工具类:
public interface ITooll{}
public class Tool:ITool{}
我想在ShellViewModel类中导入它。
如何使用CastleBoostraper进行操作?
答案 0 :(得分:2)
您需要在容器中注册视图模型和视图。较旧的Windsor版本基于属性工作,但在最新版本中,您可以使用流畅的API甚至基于某些约定的批量注册来执行此操作:
public class Bootstrapper : Bootstrapper<IShellViewModel>
{
protected override IServiceLocator CreateContainer()
{
_container = new WindsorContainer();
var adapter = new WindsorAdapter(_container);
_container.Register(Component.For<ITool>().ImplementedBy<Tool>().LifeStyle.Transient);
return adapter;
}
}
您还可以创建将在容器中注册类型的安装程序,以便您的Bootstrapper代码不会以大量注册代码结束:
public class ShellRegistration : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component.For<ITool>().ImplementedBy<Tool>().LifeStyle.Transient);
//Register other types
}
}
并在引导程序中调用它:
public class Bootstrapper : Bootstrapper<IShellViewModel>
{
protected override IServiceLocator CreateContainer()
{
_container = new WindsorContainer();
var adapter = new WindsorAdapter(_container);
_container.Install(FromAssembly.This());
return adapter;
}
}
检查我创建的Silverlight sample application,了解如何使用Castle Windsor。
您可以使用Constructor Injection或Property Injection内容来获取依赖项的实例:
public class ShellViewModel
{
public ShellViewModel(IMyDependency dependency)
{
//you'll get an instance of the class implementing IMyDependency
//Logger property will be injected after construction
}
public ILog Logger
{
get; set;
}
}