我的代码看起来像这样:
public interface IAction{
ActionType ActionType{get;}
void DoStuff();
}
public class SendEmailAction : IAction{
//i want to inject this guy
private readonly IEmailService emailService;
public SendEmailAction (IEmailService svc){
emailService = svc;
}
public ActionType ActionType{get{return ActionType.SendAnEmail;}
public void DoStuff(){
emailService.SendEmail(subject, message, etc)
}
}
我希望能够将我的服务注入我的IActions中,这将依赖于他们的工作依赖于不同的服务。问题是这些将通过Newtonsoft.Json和自定义JsonConverter反序列化,因此我可以反序列化为适当的具体类型。
public class ActionConverter : Newtonsoft.Json.JsonConverter
{
public ActionConverter()
{
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(IAction));
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Load(reader);
object dObject;
// instantiate the correct concrete type based on the actiontype
switch ((ActionType)o.Value<byte>("ActionType"))
{
case ActionType.SendAnEmail :
return o.ToObject<SendEmailAction>(serializer);
default:
return null;
}
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
我尝试使用属性注入,但是没有访问内核的权限,因此我似乎必须使用服务位置来获取内核,然后使用内核来执行kernel.Inject(objectType)。
有没有正确的方法呢?