我有两个项目:一个标准 Web Api 项目和一个包含所有 Controller 的类库项目。在 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();
}
}
Controller :
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 项目中。当我在同一个项目中拥有 Controller 时,该属性正在解析,但一旦我创建了不同的项目,仍然会发现 Controller ,但该属性未连接。
有什么想法可能是什么问题吗?
非常感谢。
最佳答案
我按照 nemesv 给我的提示进行操作并使其正常工作。基本上缺少了一些东西,但注册覆盖和 LoadFile 的使用绝对是一个问题。
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())
.AsImplementedInterfaces()
.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.LoadFrom).ToArray()
: Directory.GetFiles(path, "*.dll").Where(x => !x.Contains(".Controllers")).Select(Assembly.LoadFrom).ToArray();
}
关于c# - Autofac 无法解析外部 Controller 上的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20902848/