的通用對象的autofac裝飾是CQRS的實現:如何註冊爲CQRS
public interface IQuery<TResult> {}
public interface IQueryHandler<in TQuery, TResult>
where TQuery : IQuery<TResult>
{
Task<TResult> HandleAsync(TQuery query);
}
public interface IQueryDispatcher
{
Task<TResult> DispatchAsync<TQuery, TResult>(TQuery query)
where TQuery : IQuery<TResult>;
}
public class QueryDispatcher : IQueryDispatcher
{
private readonly IComponentContext resolver;
public QueryDispatcher(IComponentContext resolver)
{
if (resolver == null)
{
throw new ArgumentNullException(nameof(resolver));
}
this.resolver = resolver;
}
public async Task<TResult> DispatchAsync<TQuery, TResult>(TQuery query)
where TQuery : IQuery<TResult>
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
var handler = resolver.Resolve<IQueryHandler<TQuery, TResult>>();
return await handler.HandleAsync(query);
}
}
我要創建的通用查詢:
public class GetEntitiesQuery<TEntity> : IQuery<IQueryable<TEntity>>
where TEntity : Entity
{
}
public class GetEntitiesQueryHandler<TEntity> : IQueryHandler<GetEntitiesQuery<TEntity>, IQueryable<TEntity>>
where TEntity : Entity
{
// this code ...
}
我想註冊通用類如下:
builder.RegisterType<QueryDispatcher>().As<IQueryDispatcher>().InstancePerLifetimeScope();
builder.RegisterAssemblyTypes(assemblies)
.As(type => type.GetInterfaces()
.Where(interfaceType => interfaceType.IsClosedTypeOf(typeof(IQueryHandler<,>)))
.Select(interfaceType => new KeyedService("QueryHandler", interfaceType)))
.InstancePerLifetimeScope();
並拋出錯誤IQueryHandler尚未註冊
Autofac可以嗎?
不要工作這兩種解決方案。也許是GetEntitiesQueryHandler和GetEntitiesQuery '半封閉'泛型組件,試圖註冊裝飾器,不起作用。 –
Edwok
http://stackoverflow.com/questions/27509729/registering-half-closed-generic-component – Edwok
如何與Autofac? – Edwok