C# 使用windsor从另一个对象调用方法解决依赖关系
我有一个名为IContent的接口,我在几个类中实现了它,当创建实例时,我需要从数据库中获取每个IContent的属性值,我有一个contentAppService,它有一个从db获取属性值的IContent的方法,并创建IContent的实例:C# 使用windsor从另一个对象调用方法解决依赖关系,c#,dependency-injection,castle-windsor,C#,Dependency Injection,Castle Windsor,我有一个名为IContent的接口,我在几个类中实现了它,当创建实例时,我需要从数据库中获取每个IContent的属性值,我有一个contentAppService,它有一个从db获取属性值的IContent的方法,并创建IContent的实例: public interface IContent { } public class PostContent : IContent { public string Title{set;get;} public string Content {se
public interface IContent {
}
public class PostContent : IContent {
public string Title{set;get;}
public string Content {set;get;}
}
public class contentAppService : appserviceBase
{
public T GetContent<T>() where T:class,IContent
{
//some code to create instance of IContent
}
}
在windsor注册中,我需要检测请求对象的类型,如果是IContent类型,则调用contentAppService.GetContent来创建实例
在AutoFac中,我们可以实现IRegistrationSource来解决这个问题,但在windsor,我不知道如何解决这个问题。GetContent()
可以在FactoryMethod中使用。
您可以尝试以下方法:
public class HomeController
{
private PostContent _postContent;
public HomeController(PostContent postContent)
{
_postContent=postContent;
}
}
Func<IKernel, CreationContext, IContent> factoryMethod = (k, cc) =>
{
var requestedType = cc.RequestedType; // e.g. typeof(PostContent)
var contentAppService = new ContentAppService();
var method = typeof(ContentAppService).GetMethod("GetContent")
.MakeGenericMethod(requestedType);
IContent result = (IContent)method
.Invoke(contentAppService, null); // invoking GetContent<> via reflection
return result;
};
var container = new WindsorContainer();
container.Register( // registration
Classes.FromThisAssembly()// selection an assembly
.BasedOn<IContent>() // filtering types to register
.Configure(r => r.UsingFactoryMethod(factoryMethod)) // using factoryMethod
.LifestyleTransient());
var postContent = container.Resolve<PostContent>(); // requesting PostContent
Func factoryMethod=(k,cc)=>
{
var requestedType=cc.requestedType;//例如typeof(PostContent)
var contentAppService=new contentAppService();
var method=typeof(ContentAppService).GetMethod(“GetContent”)
.MakeGenericMethod(requestedType);
IContent结果=(IContent)方法
.Invoke(contentAppService,null);//通过反射调用GetContent
返回结果;
};
var container=新的WindsorContainer();
container.Register(//注册
Classes.FromThisAssembly()//选择一个程序集
.BasedOn()//筛选要注册的类型
.Configure(r=>r.UsingFactoryMethod(factoryMethod))//使用factoryMethod
.生活方式(暂时的);
var postContent=container.Resolve();//请求后内容
非常感谢,我也尝试了同样的方法,但我不知道如何获得请求的类型。我会试试你的代码。