1
我已經啓動了一個Web API項目,並將其擴展爲一個正常的MVC項目。我的意思是我有一些控制器來自ApiController
和其他來自Controller
。Web API和MVC 4控制器中使用StructureMap的問題
這裏是我的DependencyResolver:
public class StructureMapDependencyResolver :IDependencyResolver
{
public IDependencyScope BeginScope()
{
return this;
}
public StructureMapDependencyResolver(IContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
if (serviceType.IsAbstract || serviceType.IsInterface)
return _container.TryGetInstance(serviceType);
return _container.GetInstance(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances<object>()
.Where(s => s.GetType() == serviceType);
}
private readonly IContainer _container;
public void Dispose() { }
}
,這裏是我的Global.asax.cs:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ObjectFactory.Initialize(x =>
{
x.For<IDataService>().Use<MockDataService>();
});
ObjectFactory.Configure(x => x.Scan(scan =>
{
scan.AssembliesFromApplicationBaseDirectory();
scan.LookForRegistries();
scan.TheCallingAssembly();
scan.WithDefaultConventions();
}));
var container = ObjectFactory.Container;
GlobalConfiguration.Configuration.DependencyResolver =
new StructureMapDependencyResolver(container);
}
在Web API控制器工作的偉大,但我不能讓構造器注入到工作中Controller
來自派生的。當然這是通常的No parameterless constructor defined for this object
錯誤信息。
我在這裏有點損失......這是我第一次進入Web API,因此我不確定我要出錯的地方。