所以让我们开始吧:
public interface IUrl
{
Url Url { get; }
}
internal class ControllerBasedUrl : IUrl
{
public ControllerBasedUrl(string controllerName)
{
this.Url = null; // implement
}
public Url Url { get; private set; }
}
internal class AppConfigBasedUrl : IUrl
{
public AppConfigBasedUrl()
{
this.Url = null; // implement
}
public Url Url { get; private set; }
}
您可以使用多种方法:
a) 让应用程序知道您是在 Web 应用程序还是控制台应用程序中运行,然后使用条件绑定:
var kernel = new StandardKernel();
if (runningInConsoleApplication)
{
kernel.Bind<IUrl>().To<AppConfigBasedUrl>();
}
else
{
kernel.Bind<IUrl>().ToMethod(ctx =>
{
IRequest controllerRequest = ctx.Request.TraverseRequestChainAndFindMatch(x => x.Target.Name.EndsWith("Controller"));
return new ControllerBasedUrl(controllerRequest.Target.Type.Name);
});
}
b) 使 url 的绑定以它是否被注入控制器为条件:
var kernel = new StandardKernel();
kernel.Bind<IUrl>().ToMethod(ctx =>
{
IRequest controllerRequest = ctx.Request.TraverseRequestChainAndFindMatch(x => x.Target.Name.EndsWith("Controller"));
if (controllerRequest != null)
{
return new ControllerBasedUrl(controllerRequest.Target.Type.Name);
}
return new AppConfigBasedUrl();
});
都使用这个扩展:
public static class RequestExtensions
{
public static IRequest TraverseRequestChainAndFindMatch(this IRequest request, Func<IRequest, bool> matcher)
{
if (matcher(request))
{
return request;
}
if (request.ParentRequest != null)
{
return request.ParentRequest.TraverseRequestChainAndFindMatch(matcher);
}
return null;
}
}