我有这样的界面:
public interface ICategoryFacade
{
IEnumerable<Category> Get();
Category Get(int id);
int Post(Category model);
int Put(Category model);
int Patch(Category model);
int Delete(int id);
}
我上课了:
public class CategoryFacade : ICategoryFacade
{
MyContext _dbContext = new MyContext ();
public IEnumerable<Category> Get()
{
return _dbContext.Categories;
}
public Category Get(int id)
{
return _dbContext.Categories.FirstOrDefault(m => m.CategoryID == id);
}
public int Post(Category model)
{
return 0;
}
public int Put(Category model)
{
return 0;
}
public int Patch(Category model)
{
return 0;
}
public int Delete(int id)
{
return 0;
}
}
现在我想将IOC与我的ODATA控制器一起使用。所以为了做到这一点,我在Global.asax文件(Application_Start事件)中使用以下代码行:
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterInstance(new CategoryFacade()).As<ICategoryFacade>();
builder.RegisterInstance(new TVideoFacade()).As<ITVideoFacade>();
builder.RegisterType<CategoryController>();
//builder.RegisterType<CategoryFacade>().As<ICategoryFacade>();
//builder.RegisterType<TVideoFacade>().As<ITVideoFacade>();
//builder.Register(c => new CategoryFacade()).As<ICategoryFacade>().InstancePerRequest();
//builder.Register(c => new TVideoFacade()).As<ITVideoFacade>().InstancePerRequest();
var container = builder.Build();
var resolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
但它显示以下异常:
Additional information: The type 'ABC.ABCDatabase.Facades.TVideoFacade' is not assignable to service 'ABC.ABCDatabase.Abstractions.ICategoryFacade'.
你能告诉我在OData控制器上使用autofac的正确方法吗?我是autofac的新手。
答案 0 :(得分:12)
我认为你还没有在TVideoFacade类中实现ITVideoFacade接口。 只需去确保你已经在TVideoFacade类中实现了ITVideoFacade接口。
答案 1 :(得分:0)
您可以使用以下方式向autofac容器注册特定类型。但请确保您的ABC.ABCDatabase.Facades.TVideoFacade类已实现ABC.ABCDatabase.Abstractions.ICategoryFacade接口。
builder.RegisterType<ABC.ABCDatabase.Facades.TVideoFacade>()
.As<ABC.ABCDatabase.Abstractions.ICategoryFacade>()
.InstancePerLifetimeScope();
您可以根据业务需求和可行性设置生命周期和范围。
答案 2 :(得分:0)
尝试做:
builder.Register(x => new TVideoFacade()).As<ITVideoFacade>();