我尝试了很多方法,但没有运气。 我该如何解决IWindowService?
这就是我所拥有的:
var c = new UnityContainer();
c.RegisterType<IvmMain, vmMain>("mvm");
c.RegisterType<IWindow, MainWindow>("mw");
c.RegisterType(typeof(IWindowService<IvmMain>), typeof(WindowService<vmMain>),"win",
new InjectionConstructor(new ResolvedParameter<IWindow>("mw")),
new InjectionConstructor(new ResolvedParameter<IvmMain>("mvm")));
窗口服务的实现:
public class WindowService<TViewModel> : IWindowService<TViewModel>
{
readonly Window _win;
TViewModel _vm;
public WindowService(IWindow win, TViewModel vm)
{
_vm = vm;
_win = win as Window;
_win.DataContext = vm;
}
错误: WindowService类型没有带参数的构造函数(IWindow)。
答案 0 :(得分:2)
这是一个有效的例子。在您提供的方案中,没有理由进行命名注册,因此我删除了它们。但是如果你真的想要的话,我相信你可以让它与它们合作。
关键是要注册IWindowService
:
container.RegisterType(typeof (IWindowService<>), typeof (WindowService<>))
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Registering dependencies ...");
var container = new UnityContainer();
container.RegisterType(typeof (IWindowService<>), typeof (WindowService<>));
container.RegisterType<IWindow, Window>();
container.RegisterType<IvmMain, ViewModel>(); // Or possibly RegisterInstance ?
var foo = container.Resolve<IWindowService<IvmMain>>();
Console.ReadKey();
}
}
public interface IWindowService<T>
{
}
public interface IWindow
{
}
public interface IvmMain
{
}
public class ViewModel : IvmMain
{
}
public class Window : IWindow
{
}
public class WindowService<TViewModel> : IWindowService<TViewModel>
{
public WindowService(IWindow win, TViewModel vm)
{
}
}