gpt4 book ai didi

c# - 无法解决与 Unity 和 WebAPI 的依赖关系

转载 作者:太空宇宙 更新时间:2023-11-03 13:12:15 27 4
gpt4 key购买 nike

尝试在 WebAPI 中运行我的 Controller 操作时,我收到了这个奇怪的错误:

An error occurred when trying to create a controller of type 'PostController'. Make sure that the controller has a parameterless public constructor.
Resolution of the dependency failed, type = "Example.Controllers.PostController", name = "(none)".

异常发生在:调用构造函数 Example.Models.PostRepository() 时。异常是:NullReferenceException - 未将对象引用设置为对象的实例。

这是有问题的代码:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var container = new UnityContainer();
container.RegisterType<IPostRepository, PostRepository>(new HierarchicalLifetimeManager());

config.DependencyResolver = new UnityResolver(container);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ExampleApi",
routeTemplate: "api/{controller}"
);
}
}

public class PostController : ApiController
{
IPostRepository _repository;

public PostController(IPostRepository repository)
{
_repository = repository;
}

public IEnumerable<Post> GetAllProducts()
{
return _repository.GetAll();
}
}

public class PostRepository : IPostRepository
{
private IDbConnection _connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);

public IEnumerable<Post> GetAll()
{
return _connection.Query<Post>("SELECT * FROM Posts").ToList();
}
}

public class UnityResolver : IDependencyResolver
{
protected IUnityContainer Container;

public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}

this.Container = container;
}

public object GetService(Type serviceType)
{
if (!Container.IsRegistered(serviceType))
{
if (serviceType.IsAbstract || serviceType.IsInterface)
{
return null;
}
}

return Container.Resolve(serviceType);
}

public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return Container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}

public IDependencyScope BeginScope()
{
var child = Container.CreateChildContainer();
return new UnityResolver(child);
}

public void Dispose()
{
Container.Dispose();
}
}

有没有人知道可能是什么原因?我遵循了本教程:http://www.asp.net/web-api/overview/advanced/dependency-injection

最佳答案

根据我的经验,当我看到此消息时,它通常无法构建某些依赖项或缺少依赖项。您已将 IPostRepository 注册到 PostRepository,这样看起来不错。 PostRepository 中创建的 SqlConnection 呢?您能否仅针对存储库运行一些测试代码,看看它是否可以自行构建?​​

在浏览您的代码时,还会检查是否有接口(interface)阻止您解析 UnityResolver 类中的 IPostRepository?

    if (serviceType.IsAbstract || serviceType.IsInterface)
{
return null;
}

关于c# - 无法解决与 Unity 和 WebAPI 的依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28015668/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com