Skip to content

Instantly share code, notes, and snippets.

@QuantumHive
Created October 16, 2017 19:41
Show Gist options
  • Save QuantumHive/697c6a7cdb680f66d9e52f5740154e21 to your computer and use it in GitHub Desktop.
Save QuantumHive/697c6a7cdb680f66d9e52f5740154e21 to your computer and use it in GitHub Desktop.
simpleinjector conditional register example
using System;
using System.Collections.Generic;
using System.Linq;
using SimpleInjector;
namespace ConsoleApp2
{
internal class Program
{
private readonly IQueryHandler<Query, PaginatedResult<Model>> handler;
public Program(IQueryHandler<Query, PaginatedResult<Model>> handler)
{
this.handler = handler;
}
private static void Main()
{
var container = new Container();
Type Factory(TypeFactoryContext context)
{
var queryType = context.ServiceType.GetGenericArguments()[0];
var modelType = context.ServiceType.GetGenericArguments()[1].GetGenericArguments()[0];
return typeof(Interceptor<,>).MakeGenericType(queryType, modelType);
}
bool Predicate(PredicateContext context) =>
context.ServiceType.GetGenericArguments()[0].GetInterfaces()
.Any(i => i.GetGenericTypeDefinition() == typeof(PaginatedQuery<>));
container.RegisterConditional(typeof(IQueryHandler<,>), Factory, Lifestyle.Singleton, Predicate);
container.Register(typeof(IQueryHandler<,>), new[] { typeof(Program).Assembly });
container.Register<Program>();
container.Verify();
}
}
internal class Handler : IQueryHandler<Query, IEnumerable<Model>>
{
public IEnumerable<Model> Handle(Query query)
{
throw new System.NotImplementedException();
}
}
internal class Decorator<TQuery, TResult> : IQueryHandler<TQuery, TResult>
where TQuery : IQuery<TResult>
{
private readonly IQueryHandler<TQuery, TResult> decoratee;
public Decorator(IQueryHandler<TQuery, TResult> decoratee)
{
this.decoratee = decoratee;
}
public TResult Handle(TQuery query)
{
throw new System.NotImplementedException();
}
}
internal class Interceptor<TQuery, TModel> : IQueryHandler<TQuery, PaginatedResult<TModel>>
where TQuery : PaginatedQuery<TModel>
{
private readonly IQueryHandler<TQuery, IEnumerable<TModel>> handler;
public Interceptor(IQueryHandler<TQuery, IEnumerable<TModel>> handler)
{
this.handler = handler;
}
public PaginatedResult<TModel> Handle(TQuery query)
{
throw new System.NotImplementedException();
}
}
internal interface IQueryHandler<TQuery, TResult>
where TQuery : IQuery<TResult>
{
TResult Handle(TQuery query);
}
internal interface IQuery<TResult> { }
internal class PaginatedQuery<TModel> : IQuery<IEnumerable<TModel>>, IQuery<PaginatedResult<TModel>>
{ }
internal class PaginatedResult<TModel> { }
internal class Query : PaginatedQuery<Model> { }
internal class Model { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment