在WPF / CaliburnMicro / AutoFac中创建一个通用的ViewModelFactory

时间:2015-09-18 20:57:11

标签: c# wpf generics autofac caliburn.micro

我有一个使用Caliburn.Micro和AutoFac的WPF应用程序

在Bootstrapper.Configure()中,我注册了我的观点& ViewModels为:

protected override void Configure()
{
    var builder = new ContainerBuilder();
    //  register view models
    builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray())
        .Where(type => type.Name.EndsWith("ViewModel"))
        .AsSelf()
        .InstancePerDependency();
    //  register views
    builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray())
        .Where(type => type.Name.EndsWith("View"))
        .AsSelf()
        .InstancePerDependency();

    builder.Register<IWindowManager>(c => new WindowManager()).InstancePerLifetimeScope();

    _container = builder.Build();
}

    protected override IEnumerable<Assembly> SelectAssemblies()
{
    return new[]
    {
        typeof (MainViewModel).Assembly, // assembly that holds all the ViewModels
        typeof (MainView).Assembly // assembly that holds all the Views
    };
}

这很好用,视图和视图模型很好地映射了这个约定,例如。在实例化RandomViewModel时,会显示RandomView。

此外,我有很多源于通用基类的编辑/列表视图模型,其中泛型类型是我解决方案中的实体。

例如,当我有实体UserEntity,OrderEntity,AccountEntity等... 然后我会创建类:

//base classes
abstract class EditViewModelBase<T> : IEditViewModelBase where T: IEntity
abstract class ListViewModelBase<T> : IListViewModelBase where T: IEntity

//implementations
class UserEditViewModel : EditViewModelBase<UserEntity> {...}
class OrderEditViewModel : EditViewModelBase<OrderEntity> {...}
class AccountEditViewModel : EditViewModelBase<AccountEntity> {...}
...
class UserListViewModel : ListViewModelBase<UserEntity> {...}
class OrderListViewModel : ListViewModelBase<OrderEntity> {...}
class UserListViewModel : ListViewModelBase<UserEntity> {...}
...

现在我想创建一个ViewModelFactory来以通用的方式定位视图模型:

class ViewModelFactory
{
    public IEditViewModelBase CreateEditViewModel<T>()
    {
        //this method should do :
        // if typeof(T) == typeof(UserEntity) return new UserEditViewModel();
        // if typeof(T) == typeof(OrderEntity) return new OrderEditViewModel();
        // if typeof(T) == typeof(UserEntity) return new UserEditViewModel();
        ...
    }

    public IListViewModelBase CreateListViewModel<T>()
    {
        //this method should do :
        // if typeof(T) == typeof(OrderEntity) return new OrderListViewModel();
        ...
    }
}

我如何解决这个问题,因此每次添加新实体和放大器时,我都不必更改ViewModelFactory。 ViewModels到我的解决方案? 我正在考虑使用像IsInstanceOf和Activator.CreateInstance这样的反射技巧来循环容器,但是我无法让它工作......

2 个答案:

答案 0 :(得分:1)

我认为最简单的方法是使用内部使用AutoFac的Auto Factory库。 您可以这样解决:

using AutoFactory;
class ViewModelFactory
{
    private IAutoFactory<IEditViewModelBase> _editFactory = Factory.Create<IEditViewModelBase>();
    private IAutoFactory<IListViewModelBase> _listFactory = Factory.Create<IListViewModelBase>();

    public IEditViewModelBase CreateEditViewModel<T>()
    {
        return _editFactory.SeekPart(t => t.BaseType.GetGenericArguments()[0].Name == typeof(T).Name);
    }

    public IListViewModelBase CreateListViewModel<T>()
    {
        return _listFactory.SeekPart(t => t.BaseType.GetGenericArguments()[0].Name == typeof(T).Name);
    }
}

或者,如果您想直接使用AutoFac,您可以执行以下操作:

using Autofac.Builder;
using Autofac.Features.Metadata
class ViewModelFactory
{
    private IContainer _container;
    private IEnumerable<Meta<Lazy<IEditViewModelBase>>> _editParts;

    public ViewModelFactory()
    {
        var builder = new ContainerBuilder();
        builder.RegisterAssemblyTypes(this.GetType().Assembly)
           .Where(t => typeof(IEditViewModelBase).IsAssignableFrom(t))
           .As<IEditViewModelBase>()
           .WithMetadata("type", t => t.BaseType.GetGenericArguments()[0]);
        _container = builder.Build();
        _editParts = _container.Resolve<IEnumerable<Meta<Lazy<IEditViewModelBase>>>>();
    }

    public IEditViewModelBase CreateEditViewModel<T>()
    {
        return _editParts.FirstOrDefault(p => p.Metadata["type"] as Type == typeof(T)).Value.Value;
    }
    ...
}

答案 1 :(得分:0)

我叮叮当当

public class Bootstrapper
{
  public IContainer Bootstrap()
  {
    var builder = new ContainerBuilder();

    builder.RegisterType<EventAggregator>().As<IEventAggregator>().SingleInstance();
    builder.RegisterType<MessageDialogService>().As<IMessageDialogService>();

    builder.RegisterType<FileDataService>().As<IDataService>();
    builder.RegisterType<fLookupProvider>().As<ILookupProvider<f>>();
    builder.RegisterType<fGroupLookupProvider>().As<ILookupProvider<fGroup>>();
    builder.RegisterType<fDataProvider>().As<IfDataProvider>();

    builder.RegisterType<fEditViewModel>().As<IfEditViewModel>();
    builder.RegisterType<NavigationViewModel>().As<INavigationViewModel>();
    builder.RegisterType<MainViewModel>().AsSelf();

    return builder.Build();
  }
}