這是一個後續行動Generic Interface dependency injection into factoryNinject綁定通用接口
答案是正確的,但我過於簡單的代碼。因爲在界面上使用out參數,所以不能將TOrderRequest作爲create方法中的輸入參數。並且在界面上使用Out和In時,綁定將不再起作用。
那麼你如何將這與Ninject綁定?
using System;
using Ninject;
using System.Collections.Generic;
using System.Linq;
namespace NinjectPlayGround
{
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel();
//How to bind this?
kernel.Bind(typeof(ICreateOrders<,>)).To<HorseOrderCreator>();
//kernel.Bind<ICreateOrders<IOrderRequest, IOrderResponse>>().To(typeof(OrderCreator));
kernel.Bind<IOrderCreatorFactory>().To<OrderCreatorFactory>();
var factory = kernel.Get<IOrderCreatorFactory>();
var orderCreator = factory.GetOrderCreator(new OrderRequest());
var create = orderCreator.Create(new OrderRequest());
}
}
public class OrderRequest : IOrderRequest
{
}
public class OrderResponse : IOrderResponse
{
}
public class HorseOrderRequest : IOrderRequest
{
}
public class HorseOrderResponse : IOrderResponse
{
public string HorseName { get; set; }
}
public class HorseOrderCreator : ICreateOrders<HorseOrderRequest, HorseOrderResponse>
{
public HorseOrderResponse Create(HorseOrderRequest orderRequest)
{
return new HorseOrderResponse() { HorseName = "Fred" };
}
}
public class OrderCreator : ICreateOrders<OrderRequest, OrderResponse>
{
public OrderResponse Create(OrderRequest orderRequest)
{
throw new NotImplementedException();
}
}
public class OrderCreatorFactory : IOrderCreatorFactory
{
private readonly IEnumerable<ICreateOrders<IOrderRequest, IOrderResponse>> createOrders;
public OrderCreatorFactory(IEnumerable<ICreateOrders<IOrderRequest, IOrderResponse>> createOrders)
{
this.createOrders = createOrders;
}
public ICreateOrders<IOrderRequest, IOrderResponse> GetOrderCreator(IOrderRequest orderRequest)
{
//Based on orderRequest i find the implementation i need.
}
}
public interface ICreateOrders<TOrderRequest, TOrderResponse> where TOrderRequest : IOrderRequest where TOrderResponse : IOrderResponse
{
TOrderResponse Create(TOrderRequest orderRequest);
}
public interface IOrderCreatorFactory
{
ICreateOrders<IOrderRequest, IOrderResponse> GetOrderCreator(IOrderRequest orderRequest);
}
public interface IOrderRequest
{
}
public interface IOrderResponse
{
}
}
輝煌。謝謝@jbl。 – MacGyver