C# 从Castle Winsdor自动解析
我正在尝试将我的模型、视图和视图模型分离到不同的组件中,并用Castle Windsor对它们进行实例化 我有我的app.configC# 从Castle Winsdor自动解析,c#,mvvm,dependency-injection,inversion-of-control,castle-windsor,C#,Mvvm,Dependency Injection,Inversion Of Control,Castle Windsor,我正在尝试将我的模型、视图和视图模型分离到不同的组件中,并用Castle Windsor对它们进行实例化 我有我的app.config <components> <component id="ViewModel.SomeViewModel" service="TEST.Business.IViewModel, TEST.Business" type="TEST.ViewModel.SomeViewModel, Test.ViewModel" /> <comp
<components>
<component id="ViewModel.SomeViewModel" service="TEST.Business.IViewModel, TEST.Business" type="TEST.ViewModel.SomeViewModel, Test.ViewModel" />
<component id="ViewModel.SomeView" service="TEST.Business.IView, TEST.Business" type="TEST.View.SomeView, Test.View" />
</components>
并通过
IoC.Configure();
var viewModel = IoC.Resolve<IViewModel>();
var view = IoC.Resolve<IView>();
view.ShowDialog();
IoC.Configure();
var viewModel=IoC.Resolve();
var view=IoC.Resolve();
view.ShowDialog();
我的静态IoC课程
public static class IoC
{
private static IWindsorContainer container;
public static void Configure()
{
IResource resource = new ConfigResource("castle");
container = new WindsorContainer(new XmlInterpreter(resource));
}
public static TService Resolve<TService>()
{
return container.Resolve<TService>();
}
}
公共静态类IoC
{
私有静态IWindsorContainer;
公共静态void Configure()
{
IResource资源=新配置资源(“城堡”);
容器=新的WindsorContainer(新的XML解释器(资源));
}
公共静态TService解析()
{
返回container.Resolve();
}
}
直到现在都很简单
但我愿意这样做:
命名必须是这样的:I[someName]视图模型和I[someName]视图
然后解析my app.config中的每个组件,从而为每对视图和ViewModel解析并关联它们
我想有很多方法可以解决我的问题,但我不知道该用哪个关键词
顺便说一句:I[someName]ViewModel和View是ofc IViewModels和IViews,它们使用反射来迭代要解析的程序集中的类型。您可以使用
类
进行注册
var assembly = Assembly.GetExecutingAssembly(); // Replace with the assembly you want to resolve for.
var exports = assembly.ExportedTypes;
var viewTypes = exports.Where(t => t.GetInterface(typeof(IView).FullName) != null);
foreach (var viewType in viewTypes)
{
var viewModelType = assembly.GetType(viewType.FullName.Replace("View", "ViewModel"));
var viewModel = container.Resolve(viewModelType);
var view = container.Resolve(viewType);
view.ShowDialog();
}
在您的示例中,我看不到IViewModel和IView之间有任何依赖关系,因此您的代码没有意义。如果视图模型作为构造函数的参数注入,它将自动解析
我不建议使用这种技术。它可能比需要的更复杂。你确定你真的了解如何使用IoC容器/温莎城堡吗 我认为你做错了
不要抽象视图和视图模型。这对你没有好处。因此,问题是架构问题,而不是技术问题。一旦你习惯了Ioc容器,它就非常棒了。通常,您只希望从应用程序的主/引导代码使用容器。在我看来,您似乎试图使容器的resolve函数成为静态的,以允许在任何地方解析组件。这是不必要的 如果您正在寻找一种以良好方式绑定视图和视图模型的方法,请查看caliburn micro。您可以将其与大多数Ioc容器(包括windsor)结合使用 亲切问候,
Marwijn.“真的很简单”?这看起来确实有点过度设计。您应该更喜欢依赖注入,而不是解析所有类型。我想我还是像以前一样保留它吧。我只是想学习新东西,所以我对我描述的这种特殊方式很感兴趣。如果疼痛,可能是有原因的。