控制器注册为瞬态,但实现IDisposable

时间:2018-04-26 11:29:37

标签: c# .net asp.net-web-api dependency-injection simple-injector

var container = new Container();

container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

container.RegisterInstance<IDbConnection>(new SqlConnection(connectionString));

container.Register<IAdvertRepository, AdvertRepository>(Lifestyle.Scoped);

container.Register<IAdvertService, AdvertService>(Lifestyle.Scoped);
container.Register<ICommentService, CommentService>(Lifestyle.Scoped);
container.Register<IRoleService, RoleService>(Lifestyle.Scoped);
container.Register<IUserService, UserService>(Lifestyle.Scoped);

container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

container.Verify();
GlobalConfiguration.Configuration.DependencyResolver =
    new SimpleInjectorWebApiDependencyResolver(container);

我在Web API中使用Simple Injector并尝试使用它,但得到错误:

  

AdvertController注册为transient,但实现了IDisposable

其他控制器具有相同的错误。

我该如何解决?

public class AdvertController : ApiController
{
    private readonly IAdvertService _advertService;

    public AdvertController(IAdvertService advertService)
    {
        _advertService = advertService;
    }

    [HttpGet]
    public IEnumerable<AdvertDto> GetAll()
    {
        return _advertService.GetAll();
    }

    [HttpGet]
    public AdvertDto Get(long id)
    {
        return _advertService.Get(id);
    }

    [HttpDelete]
    public void Delete(long id)
    {
        _advertService.Delete(id);
    }
}

1 个答案:

答案 0 :(得分:1)

对于其他任何人来到这个页面,在我们的例子中,SimpleInjector自动从3.1.1更新到4.3.0,因为另一个包依赖于新版本,这打破了我们的MVC5应用程序

  

XXXController注册为transient,但实现了IDisposable

经过一番调查后,我意识到当 SimpleInjector 更新时,没有其他相关软件包( SimpleInjector.Integration.Web SimpleInjector.Integration.Web .Mvc 等)曾经。我更新了这些,还必须更改

的所有实例
container.RegisterPerWebRequest<T>(...)

container.Register<T>(..., Lifestyle.Scoped)

之后一切都恢复了。

P.S。对于任何注意到其他包不应该依赖于SimpleInjector的人来说,你是完全正确的。这是一个内部生成的软件包,不知何故意外添加了依赖项。我们删除了它,但也认为最好能够使用最新的SI软件包。