使用windsor解析来自另一个对象的调用方法的依赖关系

问题描述 投票:1回答:1

我有一个名为IContent的接口,我在几个类中实现它,在创建实例时,我需要从数据库获取每个icontent的属性值,我有一个contentAppService,它有一个方法来获取一个icontent,从db获取属性值并创建icontent实例:

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
}
}

在控制器中我写这样的代码:

public class HomeController
{
 private PostContent _postContent;
 public HomeController(PostContent  postContent)
 {
  _postContent=postContent;
}
}

在windsor注册中,我需要检测所请求对象的类型,如果是类型为IContent,则调用contentAppService.GetContent来创建实例。

在AutoFac中我们可以实现IRegistrationSource来解决这个问题,但在windsor我不知道如何解决这个问题。

c# dependency-injection castle-windsor
1个回答
2
投票

GetContent<T>()可以在FactoryMethod中使用。你可以尝试这样的事情:

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
© www.soinside.com 2019 - 2024. All rights reserved.