好的,我对this answer 有一个书呆子迷,所以我不得不分享我添加到它以支持我的 ctor 注入的这个抽象工厂。
using System;
using System.Collections.ObjectModel;
namespace MVVM
{
public class ObservableVMCollectionFactory<TModel, TViewModel>
: IVMCollectionFactory<TModel, TViewModel>
where TModel : class
where TViewModel : class
{
private readonly IVMFactory<TModel, TViewModel> _factory;
public ObservableVMCollectionFactory( IVMFactory<TModel, TViewModel> factory )
{
this._factory = factory.CheckForNull();
}
public ObservableCollection<TViewModel> CreateVMCollectionFrom( ObservableCollection<TModel> models )
{
Func<TModel, TViewModel> viewModelCreator = model => this._factory.CreateVMFrom(model);
return new ObservableVMCollection<TViewModel, TModel>(models, viewModelCreator);
}
}
}
以此为基础:
using System.Collections.ObjectModel;
namespace MVVM
{
public interface IVMCollectionFactory<TModel, TViewModel>
where TModel : class
where TViewModel : class
{
ObservableCollection<TViewModel> CreateVMCollectionFrom( ObservableCollection<TModel> models );
}
}
还有这个:
namespace MVVM
{
public interface IVMFactory<TModel, TViewModel>
{
TViewModel CreateVMFrom( TModel model );
}
}
这里是完整性检查器:
namespace System
{
public static class Exceptions
{
/// <summary>
/// Checks for null.
/// </summary>
/// <param name="thing">The thing.</param>
/// <param name="message">The message.</param>
public static T CheckForNull<T>( this T thing, string message )
{
if ( thing == null ) throw new NullReferenceException(message);
return thing;
}
/// <summary>
/// Checks for null.
/// </summary>
/// <param name="thing">The thing.</param>
public static T CheckForNull<T>( this T thing )
{
if ( thing == null ) throw new NullReferenceException();
return thing;
}
}
}