Matt Can Code  

Conditional Resolving multiple implementation from generic interface base on types

articles

Generic type name inside the bracket can be treated as identity of the class

Dependency injection is applied where there is only one implementation to the interface, DI via constructor is mostly seen.

but if a interface has multiple implementation, resolving the right one can be done in runtime and determined by the paramterized type variables

 

[HttpPost]
public IActionResult GetAll([FromBody] GetAllQuery query)
        {
            var handleType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(List<DemoModel>));
            dynamic QueryHandler = _context.Resolve(handleType);
            return new JsonResult(QueryHandler.execute((dynamic)query));
              }

namespace DynamicDI.Query
{
    public interface IQuery<TResult>
    {
    }
}

namespace DynamicDI.Query
{
    public class GetAllQuery : IQuery<List<DemoModel>> 
    {
        public int Id { get; set; }
    }
}

namespace DynamicDI.QueryHandler
{
    interface IQueryHandler<IQuery, TResult>
    {
        TResult execute(IQuery query);
    }
}


namespace DynamicDI.QueryHandler
{
    public class GetAllQueryHandler : IQueryHandler<GetAllQuery, List<DemoModel>>
    {
        public GetAllQueryHandler()
        {
            //Here you can put repository implmentation at the constructor
        }
        public List<DemoModel> execute(GetAllQuery query)
        {
            //repo.getall
            return new List<DemoModel>
            {
                new DemoModel{Id=0, Name="Matt"},
                new DemoModel{Id=1, Name="Yang"}
             };
        }
    }
}

 

posted on 2026-01-17 09:53  Matt Yeung  阅读(0)  评论(0)    收藏  举报