简体   繁体   English

为什么在Portable Library类中我无法实例化ValidationContext以及如何修复它?

[英]Why in Portable Library classes I can't instantiate a ValidationContext and how to fix it?

I'm creating in a Portable Library Class my domain objects. 我正在可移植库类中创建我的域对象。 Those one should implement INotifyPropertChanged and INotifyDataErrorInfo 那些应该实现INotifyPropertChangedINotifyDataErrorInfo

So, my domain classes should implement this base class 所以,我的域类应该实现这个基类

public abstract class DomainObject : INotifyPropertyChanged, INotifyDataErrorInfo
{
    private ErrorsContainer<ValidationResult> errorsContainer;

    protected DomainObject() {}

    public event PropertyChangedEventHandler PropertyChanged;
    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

    public bool HasErrors
    {
        get { return this.ErrorsContainer.HasErrors; }
    }

    protected ErrorsContainer<ValidationResult> ErrorsContainer
    {
        get
        {
            if (this.errorsContainer == null)
            {
                this.errorsContainer =
                    new ErrorsContainer<ValidationResult>(pn => this.RaiseErrorsChanged(pn));
            }

            return this.errorsContainer;
        }
    }

    public IEnumerable GetErrors(string propertyName)
    {
        return this.errorsContainer.GetErrors(propertyName);
    }

    protected void RaisePropertyChanged(string propertyName)
    {
        this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, e);
        }
    }

    protected void ValidateProperty(string propertyName, object value)
    {
        if (string.IsNullOrEmpty(propertyName))
        {
            throw new ArgumentNullException("propertyName");
        }

        this.ValidateProperty(new ValidationContext(this, null, null) { MemberName = propertyName }, value);
    }

    protected virtual void ValidateProperty(ValidationContext validationContext, object value)
    {
        if (validationContext == null)
        {
            throw new ArgumentNullException("validationContext");
        }

        List<ValidationResult> validationResults = new List<ValidationResult>();
        Validator.TryValidateProperty(value, validationContext, validationResults);

        this.ErrorsContainer.SetErrors(validationContext.MemberName, validationResults);
    }

    protected void RaiseErrorsChanged(string propertyName)
    {
        this.OnErrorsChanged(new DataErrorsChangedEventArgs(propertyName));
    }

    protected virtual void OnErrorsChanged(DataErrorsChangedEventArgs e)
    {
        var handler = this.ErrorsChanged;
        if (handler != null)
        {
            handler(this, e);
        }
    }
}

But I realized that in this line 但我意识到这一点

        this.ValidateProperty(new ValidationContext(this, null, null)
           { MemberName = propertyName }, value);

I can't create the object ValidationContext because it does not have any constructor. 我无法创建ValidationContext对象,因为它没有任何构造函数。 How can I do to create the new one? 如何创建新的?

UPDATE According to my Intellisense, this contains. 更新根据我的Intellisense,这包含。

#region Assembly System.ComponentModel.DataAnnotations.dll, v2.0.5.0
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.0\Profile\Profile46\System.ComponentModel.DataAnnotations.dll
#endregion

using System;
using System.Collections.Generic;

namespace System.ComponentModel.DataAnnotations
{
    // Summary:
    //     Describes the context in which a validation check is performed.
    public sealed class ValidationContext
    {
        // Summary:
        //     Gets or sets the name of the member to validate.
        //
        // Returns:
        //     The name of the member to validate.
        public string DisplayName { get; set; }
        //
        // Summary:
        //     Gets the dictionary of key/value pairs that is associated with this context.
        //
        // Returns:
        //     The dictionary of the key/value pairs for this context.
        public IDictionary<object, object> Items { get; }
        //
        // Summary:
        //     Gets or sets the name of the member to validate.
        //
        // Returns:
        //     The name of the member to validate.
        public string MemberName { get; set; }
        //
        // Summary:
        //     Gets the object to validate.
        //
        // Returns:
        //     The object to validate.
        public object ObjectInstance { get; }
        //
        // Summary:
        //     Gets the type of the object to validate.
        //
        // Returns:
        //     The type of the object to validate.
        public Type ObjectType { get; }

        // Summary:
        //     Returns the service that provides custom validation.
        //
        // Parameters:
        //   serviceType:
        //     The type of the service to use for validation.
        //
        // Returns:
        //     An instance of the service, or null if the service is not available.
        public object GetService(Type serviceType);
    }
}

This is something we missed. 这是我们错过的。 In early builds of Visual Studio 2012, IServiceProvider was not available due to it being removed from Windows Store apps. 在Visual Studio 2012的早期版本中,IServiceProvider由于从Windows应用商店应用中删除而无法使用。 Due to the way that portable was modeled underneath this meant no other platform combination could expose it either. 由于便携式在其下方建模的方式,这意味着没有其他平台组合可以暴露它。 This caused anything that had a dependency on it to be removed, hence the ValidationContext constructor. 这导致任何依赖于它的东西被删除,因此ValidationContext构造函数。 Later we added IServiceProvider back, and missed this constructor. 后来我们又添加了IServiceProvider,并错过了这个构造函数。 I've filed a bug internally, and we'll see if we can re-add it in a future version. 我在内部提交了一个错误,我们会看看是否可以在将来的版本中重新添加它。

To workaround this, you have a couple of options: 要解决此问题,您有几个选择:

1) Target .NET Framework 4.5 and Silverlight 5. These versions added new constructors which do not have a dependency on IServiceProvider. 1)目标.NET Framework 4.5和Silverlight 5.这些版本添加了新的构造函数,它们不依赖于IServiceProvider。

2) Use Reflection to call the constructor. 2)使用Reflection来调用构造函数。 Make note that this will only work in .NET Framework and Silverlight. 请注意,这只适用于.NET Framework和Silverlight。 It will not work in Windows Store apps because it does not expose this constructor (it will throw InvalidOperationException). 它在Windows应用商店应用中不起作用,因为它不公开此构造函数(它将抛出InvalidOperationException)。

3) Have the platform-specific projects (ie .NET Framework 4.0 or Silverlight 4) projects create the ValidationContext themselves, and have it injected into the portable library. 3)让特定于平台的项目(即.NET Framework 4.0或Silverlight 4)项目自己创建ValidationContext,并将其注入可移植库。 Either you can do this via some sort of dependency injection, or via a platform-adapter pattern that I call out in Create a Continuous Client Using Portable Class Libraries under the Converting Existing Libraries to PCLs section. 您可以通过某种依赖注入,或通过我在“ 将现有库转换为PCL”部分下使用可移植类库创建连续客户端时调用的平台适配器模式来实现此目的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法访问可移植类库中的类 - Can't access classes in Portable Class Library 为什么我不能在我的可移植类库中调用Delegate.CreateDelegate? - Why can't I call Delegate.CreateDelegate in my Portable Class Library? 使用 FluentValidation 如何在 controller 中使用 validationContext 进行测试 - With FluentValidation how can I test using validationContext within a controller 为什么不能在函数中实例化对象 - Why can't I instantiate an object in a function 如何确定便携式类库中的默认编码? - How can I determine the default encoding in a portable class library? 如何确定便携式类库中的当前代码页? - How can I determine the current code page in a portable class library? 如何修复警告说实例化中缺少某些内容? - How can I fix a warning saying something is missing in instantiate? 无法访问或实例化新创建的类 - Can't access or instantiate newly created classes 我如何在IValidatableObject.Validate方法的ValidationContext参数中提供IServiceProvider - How can i have a IServiceProvider available in ValidationContext parameter of IValidatableObject.Validate method 为什么我不能在XAML中定义ResourceDictionary并单独实例化它? - Why can't I define a ResourceDictionary in XAML and instantiate it by itself?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM