I have an interface named IContent and i implement it in several classes, when creating instances i need to get properties value of each icontent from database, i have a contentAppService and it have a method to get an icontent that get properties value from db and creates instance of 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
}
}
And in controller i write code like this:
public class HomeController
{
private PostContent _postContent;
public HomeController(PostContent postContent)
{
_postContent=postContent;
}
}
In windsor registeration i need to detect type of requested object and if is of type IContent then call contentAppService.GetContent to create instance.
In AutoFac we can implement IRegistrationSource to solve this scenario, but in windsor i don't know how i can solve the problem.
GetContent<T>()
can be used inside of FactoryMethod.
You can try something like this:
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