Ale*_*lex 8 inversion-of-control nancy tinyioc
我正在建立一个小型的Nancy网络项目.
在我的一个类(不是南希模块)的方法中,我想基本上做:
var myThing = TinyIoC.TinyIoCContainer.Current.Resolve<IMyThing>();
Run Code Online (Sandbox Code Playgroud)
但是,.Current(非公共成员,_RegisteredTypes)只有一个注册 :
TinyIoC.TinyIoCContainer.TypeRegistration
当然,在上面的代码中,我得到:
无法解析类型:My.Namespace.IMyThing
所以,我想我没有在我的引导程序中注册相同的容器?
有没有办法搞定它?
编辑
为了充实我正在尝试做的事情:
基本上,我的网址结构看起来像:
/ {的myType}/{myMethod的}
所以,想法是:/ customer/ShowAllWithTheNameAlex将加载Customer服务,并执行showAllWithTheNameAlex方法
我这样做是:
public interface IService
{
void DoSomething();
IEnumerable<string> GetSomeThings();
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个抽象基类,使用返回服务的方法GetService.
在这里,我正在尝试使用TinyIoC.TinyIoCContainer.Current.Resolve();
在这种情况下,它将是TinyIoC.TinyIoCContainer.Current.Resolve("typeName");
public abstract class Service : IService
{
abstract void DoSomething();
abstract IEnumerable<string> GetSomeThings();
public static IService GetService(string type)
{
//currently, i'm doing this with reflection....
}
}
Run Code Online (Sandbox Code Playgroud)
这是我对服务的实现.
public class CustomerService : Service
{
public void DoSomething()
{
//do stuff
}
public IEnumerable<string> GetSomeThings()
{
//return stuff
}
public IEnumerable<Customer> ShowAllWithTheNameAlex()
{
//return
}
}
Run Code Online (Sandbox Code Playgroud)
最后,我有我的南希模块,看起来像:
public class MyModule : NancyModule
{
public MyModule()
{
Get["/{typeName}/{methodName}"] = p => ExecuteMethod(p.typeName, p.methodName);
}
private dynamic ExecuteMethod(string typeName, string methodName)
{
var service = Service.GetService(typeName);
var result = service.GetType().GetMethod(methodName).Invoke(service, null);
//do stuff
return result; //or whatever
}
}
Run Code Online (Sandbox Code Playgroud)
@alexjamesbrown - 简短的回答是,你不知道。Nancy 经过专门设计,因此您无需直接处理容器。您提到您想要依赖的类IMyThing不是 NancyModule。好吧,这不是问题,只要您的模块之一引用了它,那么这些依赖项也可以拥有自己的依赖项,这些依赖项将在运行时得到满足。
public interface IGreetingMessageService
{
string GetMessage();
}
public class GreetingMessageService: IGreetingMessageService
{
public string GetMessage()
{
return "Hi!";
}
}
public interface IGreeter
{
string Greet();
}
public class Greeter
{
private readonly IGreetingMessageService service;
public Greeter(IGreetingMessageService service)
{
this.service = service;
}
public string Greet()
{
return this.service.GetMessage();
}
}
public class GreetingsModule : NancyModule
{
public GreetingModule(IGreeter greeter)
{
Get["/"] = x => greeter.Greet();
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码可以正常工作,并且在运行时Greeter将依赖于满意度IGreetingMessageService
| 归档时间: |
|
| 查看次数: |
3701 次 |
| 最近记录: |