我正在尝试将System.Web.Http.ApiController
上的属性设置为已解析IServerPackageRepository
的值。控制器以HttpSelfHostServer
运行,DependencyResolver
已设置为AutofacWebApiDependencyResolver
。以下是Autofac.Module.Load
方法
...
builder.RegisterType<ServerPackageRepository>()
.As<IServerPackageRepository>()
.SingleInstance()
.WithParameter("path", this.StoragePath);
builder.RegisterApiControllers(Assembly.GetExecutingAssembly())
.PropertiesAutowired();
ApiController
控制器本身具有
public IServerPackageRepository Repository { get; set; }
但永远不会解决。
我试图这样做,因为ApiController
除了默认构造函数之外什么都不会。有关如何使用Autofac以正确方式执行此操作的任何建议吗?
答案 0 :(得分:4)
如果ApiController
仅使用默认构造函数,则听起来没有调用依赖项解析程序,并且可能无法正确注册Web API。这是一个使用构造函数注入进行自托管的工作示例。
依赖项(在本例中为简单记录器):
public interface ILogger
{
void Log(string text);
}
public class Logger : ILogger
{
public void Log(string text)
{
Debug.WriteLine(text);
}
}
一个依赖记录器的简单控制器:
public class ValuesController : ApiController
{
readonly ILogger _logger;
public ValuesController(ILogger logger)
{
_logger = logger;
}
// GET api/values
public IEnumerable<string> Get()
{
_logger.Log("GET api/values");
return new string[] { "value1", "value2" };
}
}
控制台应用程序:
class Program
{
static void Main(string[] args)
{
var configuration = new HttpSelfHostConfiguration("http://localhost:8080");
configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var builder = new ContainerBuilder();
// Register API controllers using assembly scanning.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// Register API controller dependencies.
builder.Register<ILogger>(c => new Logger()).SingleInstance();
var container = builder.Build();
// Set the dependency resolver implementation.
var resolver = new AutofacWebApiDependencyResolver(container);
configuration.DependencyResolver = resolver;
// Open the HTTP server and listen for requests.
using (var server = new HttpSelfHostServer(configuration))
{
server.OpenAsync().Wait();
Console.WriteLine("Hosting at http://localhost:8080/{controller}");
Console.ReadLine();
}
}
}
使用以下方法点击控制器操作:
http://localhost:8080/api/values
请测试一下,如果您有任何问题请告诉我。
答案 1 :(得分:2)
不确定这是否是您想要的,但您可以创建自己的基本控制器并将IServerPackageRepository
注入其中。
public class MyApiController : ApiController {
public IServerPackageRepository ServerPackageRepository { get; set; }
public MyApiController(IServerPackageRepository serverPackageRepository) {
ServerPackageRepository = serverPackageRepository;
}
}
然后,使用它作为基本控制器:
public class ProductsController : MyApiController {
public ProductsController(IServerPackageRepository serverPackageRepository)
: base(serverPackageRepository) {
}
public IEnumerable<Product> Get() {
ServerPackageRepository.DoWork();
//...
}
}
答案 2 :(得分:0)
一种替代方法是直接将您的依赖项连接到属性,如下所示:
var repo = new ServerPackageRepository(path: this.StoragePath);
builder.RegisterInstance(repo)
.SingleInstance();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly())
.WithProperty("Repository", repo)
.PropertiesAutowired();