【发布时间】:2014-01-03 11:41:21
【问题描述】:
我有两个项目:一个标准的 Web Api 项目和一个包含所有控制器的类库项目。在 Web Api 中,我在 Global.asax 类中有以下内容:
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
var builder = new ContainerBuilder();
builder.RegisterApiControllers(GetAssemblies(true)).PropertiesAutowired();
builder
.RegisterAssemblyTypes(GetAssemblies(false))
.Where(t => t.GetCustomAttributes(typeof(IocContainerMarkerAttribute), false).Any())
.PropertiesAutowired();
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(builder.Build());
}
private static Assembly[] GetAssemblies(bool isController)
{
var path = HttpContext.Current.Server.MapPath("~/Bin");
return isController
? Directory.GetFiles(path, "*.dll") .Where(x => x.Contains(".Controllers")).Select(Assembly.LoadFile).ToArray()
: Directory.GetFiles(path, "*.dll").Select(Assembly.LoadFile).ToArray();
}
}
控制器:
public class PropertyAgentController : ApiController
{
public ICommandControllerProcessor CommandControllerProcessor { get; set; }
[HttpPost]
public HttpResponseMessage HandleMessage()
{
return CommandControllerProcessor.HandleMessage(this);
}
}
和依赖:
public interface ICommandControllerProcessor
{
HttpResponseMessage HandleMessage(ApiController controller);
}
[IocContainerMarker]
public class CommandControllerProcessor : ICommandControllerProcessor
{
public virtual HttpResponseMessage HandleMessage(ApiController controller)
{
return null;
}
}
CommandControllerProcessor 类位于 web api 项目中。当我在同一个项目中拥有控制器时,该属性正在被解析,但一旦我创建了一个不同的项目,控制器仍然被发现,但该属性未连接。
对可能出现的问题有什么想法吗?
非常感谢。
【问题讨论】:
-
您是否直接在您的 web.api 项目中从类库项目中引用或使用类型?还是只在配置 autofac 时动态加载
.Controller程序集? -
一切都是用Autofac动态加载的,项目之间没有任何直接引用。谢谢
-
尝试将
GetAssemblies方法中的Assembly.LoadFile替换为Assembly.LoadFrom。您可以在此处了解不同之处:stackoverflow.com/questions/1477843/… -
没有任何区别。我可以看到在 Autofac 中注册的类型,但我仍然尝试了一下,因为可能会发生一些奇怪的事情,但它确实解决了问题。我可以在列表或注册中看到实现类型......似乎在这种特殊情况下,方法 PropertiesAutowired 没有正常工作。
-
好的,看来您正在覆盖您的注册。当您调用
GetAssemblies(false)时,它会再次重新加载您的.Controllers,因此将您的程序集加载代码更改为:return isController ? Directory.GetFiles(path, "*.dll").Where(x => x.Contains(".Controllers")).Select(Assembly.LoadFile).ToArray() : Directory.GetFiles(path, "*.dll").Where(x => !x.Contains(".Controllers")).Select(Assembly.LoadFile).ToArray();注意第二个Where中的导航!。
标签: c# c#-4.0 asp.net-web-api