我想要完成的是拥有一个单一的 wcf 服务,该服务具有(例如)一个 Insert(ICommand command) 方法,并且可以解析一个知道如何插入底层对象类型的通用服务。
我在沙盒项目上的(糟糕的)尝试在哪里。除了其他缺陷之外,该服务还允许尝试插入任何 ICommand。我是相对较新的 Unit 用户,我想知道是否有人有更好的方法来实现这一点。
class Program
{
static void Main(string[] args)
{
var cmd = new SingleCommand();
var cmd2 = new DoubleCommand();
var s = new MyWcfService();
s.Insert(cmd);
s.Insert(cmd2);
Console.ReadKey();
}
}
public interface ICommand { }
public interface ICommandService
{
void Insert(ICommand command);
}
public interface ICommandService<in T> : ICommandService where T : ICommand
{
void Insert(T command);
}
public class SingleCommand : ICommand { }
public class DoubleCommand : ICommand { }
public class SingleCommandService : ICommandService<SingleCommand>
{
public void Insert(SingleCommand singleCommand)
{
Console.WriteLine("Inserted a SingleCommand");
}
void ICommandService.Insert(ICommand command)
{
Insert((SingleCommand)command);
}
}
public class DoubleCommandService : ICommandService<DoubleCommand>
{
public void Insert(DoubleCommand doubleCommand)
{
Console.WriteLine("Inserted a DoubleCommand");
}
void ICommandService.Insert(ICommand command)
{
Insert((DoubleCommand)command);
}
}
public static class Config
{
public static UnityContainer Container = new UnityContainer();
static Config()
{
Container.RegisterType<ICommandService, SingleCommandService>(typeof(SingleCommand).Name);
Container.RegisterType<ICommandService, DoubleCommandService>(typeof(DoubleCommand).Name);
}
}
public class MyWcfService
{
public void Insert(ICommand command)
{
var foo = Config.Container.Resolve<ICommandService>(command.GetType().Name);
foo.Insert(command);
}
}