嗨,我试着在Caliburn Micro上使用Windosor Castle。到目前为止,我只使用MEF。
我找到了这个城堡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 I用户属性[Export]和[Import]。有人能帮我解决这个问题吗?
另一个问题是我有一些工具类:
public interface ITooll{}
public class Tool:ITool{}
,我想把它导入到ShellViewModel类。
我怎么能做到与城堡boostraper ?
您需要在容器中注册您的视图模型和视图。旧的Windsor版本是基于属性工作的,但在最新版本中,你可以使用fluent 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
}
}
并在bootstrapper中调用它:
public class Bootstrapper : Bootstrapper<IShellViewModel>
{
protected override IServiceLocator CreateContainer()
{
_container = new WindsorContainer();
var adapter = new WindsorAdapter(_container);
_container.Install(FromAssembly.This());
return adapter;
}
}
查看我创建的Silverlight示例应用程序,了解如何与Castle Windsor一起工作。
你可以使用构造函数注入或属性注入来获得依赖的实例:
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;
}
}