Ninject 2.1 ActivationException:激活字符串时出错

发布于 2024-09-30 09:18:35 字数 1007 浏览 6 评论 0原文

我很困惑为什么在随机绑定中收到“Ninject.ActivationException:错误激活字符串没有可用的匹配绑定,并且类型不可自绑定”。如果我保留 IMedia 的绑定,它将抛出 ActivationException,但如果我使用 CallbackProvider,它就会起作用。所有这些类的结构都相同,但具有一些不同的属性。我很困惑为什么 ILocationType、IMedia 和 IFarmDataContext 会抛出 ActivationException 而其他的则不会。有什么想法吗?

/******************************
 * Core Types
 ******************************/
Bind<IFarmDataContext>().ToProvider(new CallbackProvider<IFarmDataContext>(delegate { return new FarmDataContext(); }));

//Media
Bind<IMedia>().To<Media>(); //blows up
//Bind<IMedia>().ToProvider(new CallbackProvider<IMedia>(delegate { return new Media(); }));
Bind<IMediaType>().To<MediaType>();
Bind<IMediaRelated>().To<MediaRelated>();

//Location
Bind<ILocation>().To<Location>();
Bind<ILocationType>().ToProvider(new CallbackProvider<ILocationType>(delegate { return new LocationType(); }));
Bind<ILocationDetail>().To<LocationDetail>();

I am confused about why I am receiving "Ninject.ActivationException : Error Activating string No matching bindings are available, and the type is not self-bindable" in random bindings. If I leave the binding for IMedia in place it will throw the ActivationException, but if I use the CallbackProvider it works. All of these classes are structured the same with a few different properties. I'm confused as to why ILocationType, IMedia, and IFarmDataContext throw ActivationException while the others do not. Any ideas?

/******************************
 * Core Types
 ******************************/
Bind<IFarmDataContext>().ToProvider(new CallbackProvider<IFarmDataContext>(delegate { return new FarmDataContext(); }));

//Media
Bind<IMedia>().To<Media>(); //blows up
//Bind<IMedia>().ToProvider(new CallbackProvider<IMedia>(delegate { return new Media(); }));
Bind<IMediaType>().To<MediaType>();
Bind<IMediaRelated>().To<MediaRelated>();

//Location
Bind<ILocation>().To<Location>();
Bind<ILocationType>().ToProvider(new CallbackProvider<ILocationType>(delegate { return new LocationType(); }));
Bind<ILocationDetail>().To<LocationDetail>();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅暮の光 2024-10-07 09:18:35

Ninject 没有绑定要在 Media .ctor 中注入的“String key”;当它尝试创建依赖于 Media 的类型时,它不知道如何解决依赖关系并抛出异常。对于大多数类型,Ninject 会尝试为您创建一些东西,但是字符串和值类型不能自绑定,因为我们没有为它们提供良好的默认值,并且它可能会对使用不同基元约定的类型造成严重破坏。

您需要在绑定中添加参数值(.WithContructorArgument("key", someValue))或使用某种提供程序(您已经完成)。

Ninject doesn't have a binding for the "String key" to inject in the Media .ctor; When it tries to create a type that depends on Media, it doesn't know how to resolve the dependency and throws. For most types, Ninject would try to create something for you, but string and value types are not self-bindable as we don't have a good default value for them and it can cause havoc on types that use different conventions with primitives.

You need add a parameter value in your bindings (.WithContructorArgument("key", someValue)) or use some kind of provider (which you have done).

嗳卜坏 2024-10-07 09:18:35

下面是 IMedia 接口和 Media 实现。 Media 是一个分部类,其主类是通过 LinqToSql DBML 文件生成的。上面绑定列表中列出的所有类型都是这种情况。

public interface IMedia : IValidationDictionary, IBaseDescriptor {

    /// <summary>
    /// Returns a specific Media object specifying 
    /// if you want the full or lite version
    /// </summary>
    /// <param name="id"></param>
    /// <param name="isLite"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    IMedia Get(long id, bool isLite, DataContext context);

    /// <summary>
    /// Returns the lite version of the request Media object
    /// </summary>
    /// <param name="id"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    IMedia Get(long id, DataContext context);

    /// <summary>
    /// Returns a list of Media Objects
    /// </summary>
    /// <param name="isLite"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    ValidationList<IMedia> List(bool isLite, DataContext context);

    /// <summary>
    /// Returns a list of Media Objects with pagination capabilities
    /// </summary>
    /// <param name="isLite"></param>
    /// <param name="skip"></param>
    /// <param name="top"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    ValidationList<IMedia> List(bool isLite, int skip, int top, DataContext context);

}

public partial class Media : BaseDescriptor, IMedia {

    #region Constructors

    public Media(String key, IError error)
        : base() {
        AddError(key, error);
    }

    #endregion

    #region Properties

    public MediaType Type {
        set { if (TypeID <= 0) { MediaType = value; } }
        get { return MediaType; }
    }

    #endregion

    #region Internal Methods

    /// <summary>
    /// Truncates relationships as appropriate to reduce over-the-wire size 
    /// </summary>
    protected override void MakeLite() {
        MediaRelateds = new EntitySet<MediaRelated>();
    }

    /// <summary>
    /// Validates the values and returns true if there are no problems.
    /// </summary>
    override public bool Validate() {
        this.ClearErrors();
        if (this.TypeID <= 0) { this.AddError("TypeID", new Error(ErrorType.VALIDATION, "TypeID is missing or invalid")); }
        if (string.IsNullOrEmpty(this.Path)) { this.AddError("Path", new Error(ErrorType.VALIDATION, "Path is missing or invalid")); }
        if (this.CreatedOn.Year <= 1900) { this.AddError("CreatedOn", new Error(ErrorType.VALIDATION, "CreatedOn is missing or invalid")); }
        if (this.CreatedBy <= 0) { this.AddError("CreatedBy", new Error(ErrorType.VALIDATION, "CreatedBy is missing or invalid")); }
        if (this.UpdatedOn.Year <= 1900) { this.AddError("UpdatedOn", new Error(ErrorType.VALIDATION, "UpdatedOn is missing or invalid")); }
        if (this.UpdatedBy <= 0) { this.AddError("UpdatedBy", new Error(ErrorType.VALIDATION, "UpdatedBy is missing or invalid")); }
        if (!string.IsNullOrEmpty(this.Path) && this.Path.Length > 255) { this.AddError("Path", new Error(ErrorType.VALIDATION, "Path is longer than the maximum of 255 characters")); }
        return (this.ErrorCount == 0);
    }
    #endregion


    #region Public Methods

    public ValidationList<IMedia> List(bool isLite, DataContext context) {
        return List(isLite, 0, 0, context);
    }

    public ValidationList<IMedia> List(bool isLite, int skip, int top, DataContext context) {
        if (context == null) { context = new DataContext(); }
        var query = context.Medias.Where(x => x.DeletedOn == null);
        List<Media> results;
        if (skip > 0 || top > 0) {
            if (top > 0) {
                if (skip < 0) { skip = 0; }
                results = query.OrderBy(x => x.ID).Skip(skip).Take(top).ToList();
            } else {
                results = query.OrderBy(x => x.ID).Skip(skip).ToList();
            }
        } else {
            results = query.OrderBy(x => x.ID).ToList();
        }

        var finalResult = new ValidationList<IMedia>(new List<IMedia>());
        foreach (var result in results) {
            result.IsLite = isLite;
            finalResult.Source.Add(result);
        }
        return finalResult;
    }

    public IMedia Get(long id, DataContext context) {
        return Get(id, false, context);
    }

    public IMedia Get(long id, bool isLite, DataContext context) {
        if (context == null) { context = new DataContext(); }
        var results = context.Medias.Where(x => x.ID == id && x.DeletedOn == null).ToList();
        var result = (results.Count > 0 ? results[0] : null);
        if (result != null) {
            result.IsLite = isLite;
        }
        return result;
    }

    #endregion

}

Below are the IMedia interface and Media implementation. Media is a partial class with the primary class generated via a LinqToSql DBML file. This is the case for all of the types listed above in the list of bindings.

public interface IMedia : IValidationDictionary, IBaseDescriptor {

    /// <summary>
    /// Returns a specific Media object specifying 
    /// if you want the full or lite version
    /// </summary>
    /// <param name="id"></param>
    /// <param name="isLite"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    IMedia Get(long id, bool isLite, DataContext context);

    /// <summary>
    /// Returns the lite version of the request Media object
    /// </summary>
    /// <param name="id"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    IMedia Get(long id, DataContext context);

    /// <summary>
    /// Returns a list of Media Objects
    /// </summary>
    /// <param name="isLite"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    ValidationList<IMedia> List(bool isLite, DataContext context);

    /// <summary>
    /// Returns a list of Media Objects with pagination capabilities
    /// </summary>
    /// <param name="isLite"></param>
    /// <param name="skip"></param>
    /// <param name="top"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    ValidationList<IMedia> List(bool isLite, int skip, int top, DataContext context);

}

public partial class Media : BaseDescriptor, IMedia {

    #region Constructors

    public Media(String key, IError error)
        : base() {
        AddError(key, error);
    }

    #endregion

    #region Properties

    public MediaType Type {
        set { if (TypeID <= 0) { MediaType = value; } }
        get { return MediaType; }
    }

    #endregion

    #region Internal Methods

    /// <summary>
    /// Truncates relationships as appropriate to reduce over-the-wire size 
    /// </summary>
    protected override void MakeLite() {
        MediaRelateds = new EntitySet<MediaRelated>();
    }

    /// <summary>
    /// Validates the values and returns true if there are no problems.
    /// </summary>
    override public bool Validate() {
        this.ClearErrors();
        if (this.TypeID <= 0) { this.AddError("TypeID", new Error(ErrorType.VALIDATION, "TypeID is missing or invalid")); }
        if (string.IsNullOrEmpty(this.Path)) { this.AddError("Path", new Error(ErrorType.VALIDATION, "Path is missing or invalid")); }
        if (this.CreatedOn.Year <= 1900) { this.AddError("CreatedOn", new Error(ErrorType.VALIDATION, "CreatedOn is missing or invalid")); }
        if (this.CreatedBy <= 0) { this.AddError("CreatedBy", new Error(ErrorType.VALIDATION, "CreatedBy is missing or invalid")); }
        if (this.UpdatedOn.Year <= 1900) { this.AddError("UpdatedOn", new Error(ErrorType.VALIDATION, "UpdatedOn is missing or invalid")); }
        if (this.UpdatedBy <= 0) { this.AddError("UpdatedBy", new Error(ErrorType.VALIDATION, "UpdatedBy is missing or invalid")); }
        if (!string.IsNullOrEmpty(this.Path) && this.Path.Length > 255) { this.AddError("Path", new Error(ErrorType.VALIDATION, "Path is longer than the maximum of 255 characters")); }
        return (this.ErrorCount == 0);
    }
    #endregion


    #region Public Methods

    public ValidationList<IMedia> List(bool isLite, DataContext context) {
        return List(isLite, 0, 0, context);
    }

    public ValidationList<IMedia> List(bool isLite, int skip, int top, DataContext context) {
        if (context == null) { context = new DataContext(); }
        var query = context.Medias.Where(x => x.DeletedOn == null);
        List<Media> results;
        if (skip > 0 || top > 0) {
            if (top > 0) {
                if (skip < 0) { skip = 0; }
                results = query.OrderBy(x => x.ID).Skip(skip).Take(top).ToList();
            } else {
                results = query.OrderBy(x => x.ID).Skip(skip).ToList();
            }
        } else {
            results = query.OrderBy(x => x.ID).ToList();
        }

        var finalResult = new ValidationList<IMedia>(new List<IMedia>());
        foreach (var result in results) {
            result.IsLite = isLite;
            finalResult.Source.Add(result);
        }
        return finalResult;
    }

    public IMedia Get(long id, DataContext context) {
        return Get(id, false, context);
    }

    public IMedia Get(long id, bool isLite, DataContext context) {
        if (context == null) { context = new DataContext(); }
        var results = context.Medias.Where(x => x.ID == id && x.DeletedOn == null).ToList();
        var result = (results.Count > 0 ? results[0] : null);
        if (result != null) {
            result.IsLite = isLite;
        }
        return result;
    }

    #endregion

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文