使用Windsor,通过从另一个对象调用方法解决依赖关系

时间:2019-02-16 06:45:39

标签: c# dependency-injection castle-windsor

我有一个名为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来解决这种情况,但是在温莎,我不知道如何解决该问题。

1 个答案:

答案 0 :(得分: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