Skip to content

Commit

Permalink
Multi-targeting net5.0; fixed nullable warnings.
Browse files Browse the repository at this point in the history
  • Loading branch information
alistairjevans committed Nov 6, 2020
1 parent ab8d435 commit 6595625
Show file tree
Hide file tree
Showing 40 changed files with 122 additions and 75 deletions.
2 changes: 1 addition & 1 deletion bench/Autofac.Benchmarks/Autofac.Benchmarks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.2">
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
Expand Down
2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "3.1.302",
"version": "5.0.100-rc.2.20479.15",
"rollForward": "latestFeature"
}
}
2 changes: 1 addition & 1 deletion src/Autofac/Autofac.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<Description>Autofac is an IoC container for Microsoft .NET. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity.</Description>
<!-- VersionPrefix patched by AppVeyor -->
<VersionPrefix>0.0.1</VersionPrefix>
<TargetFrameworks>netstandard2.1;netstandard2.0</TargetFrameworks>
<TargetFrameworks>netstandard2.1;netstandard2.0;net5.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<NoWarn>$(NoWarn);CS1591;IDE0008</NoWarn>
Expand Down
2 changes: 1 addition & 1 deletion src/Autofac/Builder/IHideObjectMembers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public interface IHideObjectMembers
/// </summary>
/// <returns>Standard result.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
string ToString();
string? ToString();

/// <summary>
/// Standard System.Object member.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ public static void InjectProperties(IComponentContext context, object instance,
continue;
}

var setParameter = property.SetMethod.GetParameters()[0];
// SetMethod will be non-null if GetInjectableProperties included it.
var setParameter = property.SetMethod!.GetParameters()[0];
var valueProvider = (Func<object?>?)null;
var parameter = resolveParameters.FirstOrDefault(p => p.CanSupplyValue(setParameter, context, out valueProvider));
if (parameter != null)
Expand Down Expand Up @@ -103,7 +104,7 @@ private static IEnumerable<PropertyInfo> GetInjectableProperties(Type instanceTy

// SetMethod will be non-null if CanWrite is true.
// Don't want to inject onto static properties.
if (property.SetMethod.IsStatic)
if (property.SetMethod!.IsStatic)
{
continue;
}
Expand All @@ -115,7 +116,8 @@ private static IEnumerable<PropertyInfo> GetInjectableProperties(Type instanceTy
continue;
}

if (propertyType.IsArray && propertyType.GetElementType().IsValueType)
// GetElementType will be non-null if IsArray is true.
if (propertyType.IsArray && propertyType.GetElementType()!.IsValueType)
{
continue;
}
Expand All @@ -136,8 +138,11 @@ private static IEnumerable<PropertyInfo> GetInjectableProperties(Type instanceTy

private static Action<object, object?> MakeFastPropertySetter(PropertyInfo propertyInfo)
{
var setMethod = propertyInfo.SetMethod;
var typeInput = setMethod.DeclaringType;
// SetMethod will be non-null if we're trying to make a setter for it.
var setMethod = propertyInfo.SetMethod!;

// DeclaringType will always be set for properties.
var typeInput = setMethod.DeclaringType!;
var parameters = setMethod.GetParameters();
var parameterType = parameters[0].ParameterType;

Expand Down
4 changes: 2 additions & 2 deletions src/Autofac/Core/Activators/Reflection/BoundConstructor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,11 @@ public object Instantiate()
}
catch (TargetInvocationException ex)
{
throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, BoundConstructorResources.ExceptionDuringInstantiation, TargetConstructor, TargetConstructor.DeclaringType.Name), ex.InnerException);
throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, BoundConstructorResources.ExceptionDuringInstantiation, TargetConstructor, TargetConstructor.DeclaringType!.Name), ex.InnerException);
}
catch (Exception ex)
{
throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, BoundConstructorResources.ExceptionDuringInstantiation, TargetConstructor, TargetConstructor.DeclaringType.Name), ex);
throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, BoundConstructorResources.ExceptionDuringInstantiation, TargetConstructor, TargetConstructor.DeclaringType!.Name), ex);
}
}

Expand Down
4 changes: 3 additions & 1 deletion src/Autofac/Core/Activators/Reflection/ConstructorBinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,9 @@ public BoundConstructor Bind(IEnumerable<Parameter> availableParameters, ICompon
private static MethodCallExpression ConvertPrimitiveType(Expression valueExpression, Type conversionType)
{
var changeTypeMethod = typeof(Convert).GetRuntimeMethod(nameof(Convert.ChangeType), new[] { typeof(object), typeof(Type) });
return Expression.Call(changeTypeMethod, valueExpression, Expression.Constant(conversionType));

// changeTypeMethod will always be non-null; Convert.ChangeType definitely exists.
return Expression.Call(changeTypeMethod!, valueExpression, Expression.Constant(conversionType));
}

private static ParameterInfo? DetectIllegalParameter(ParameterInfo[] constructorArgs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ public BoundConstructor SelectConstructorBinding(BoundConstructor[] constructorB
throw new ArgumentException(MatchingSignatureConstructorSelectorResources.AtLeastOneBindingRequired);
}

var targetTypeName = constructorBindings[0].TargetConstructor.DeclaringType.Name;
// DeclaringType will be non-null for constructors.
var targetTypeName = constructorBindings[0].TargetConstructor.DeclaringType!.Name;
var signature = string.Join(", ", _signature.Select(t => t.Name).ToArray());

if (matchingCount == 0)
Expand Down
2 changes: 1 addition & 1 deletion src/Autofac/Core/AutoActivateService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ internal class AutoActivateService : Service
/// All services of this type are considered "equal".
/// </para>
/// </remarks>
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
var that = obj as AutoActivateService;
return that != null;
Expand Down
3 changes: 2 additions & 1 deletion src/Autofac/Core/Container.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,8 @@ protected override async ValueTask DisposeAsync(bool disposing)
/// </returns>
public object GetService(Type serviceType)
{
return ((IServiceProvider)_rootLifetimeScope).GetService(serviceType);
// GetService implementation on LifetimeScope either returns an object, or throws.
return ((IServiceProvider)_rootLifetimeScope).GetService(serviceType)!;
}
}
}
2 changes: 1 addition & 1 deletion src/Autofac/Core/DependencyResolutionException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public DependencyResolutionException(string message)
/// </summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The inner exception.</param>
public DependencyResolutionException(string message, Exception innerException)
public DependencyResolutionException(string message, Exception? innerException)
: base(message, innerException)
{
}
Expand Down
5 changes: 3 additions & 2 deletions src/Autofac/Core/ISharingLifetimeScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Diagnostics.CodeAnalysis;

namespace Autofac.Core
{
Expand All @@ -26,7 +27,7 @@ public interface ISharingLifetimeScope : ILifetimeScope
/// <param name="id">Key to look up.</param>
/// <param name="value">The instance that has the specified key.</param>
/// <returns><c>true</c> if the key was found; otherwise, <c>false</c>.</returns>
bool TryGetSharedInstance(Guid id, out object value);
bool TryGetSharedInstance(Guid id, [NotNullWhen(true)] out object? value);

/// <summary>
/// Try to retrieve a shared instance based on a primary GUID key and
Expand All @@ -39,7 +40,7 @@ public interface ISharingLifetimeScope : ILifetimeScope
/// </param>
/// <param name="value">The instance that has the specified keys.</param>
/// <returns><c>true</c> if the key was found; otherwise, <c>false</c>.</returns>
bool TryGetSharedInstance(Guid primaryId, Guid? qualifyingId, out object value);
bool TryGetSharedInstance(Guid primaryId, Guid? qualifyingId, [NotNullWhen(true)] out object? value);

/// <summary>
/// Creates a shared instance with a GUID key.
Expand Down
4 changes: 2 additions & 2 deletions src/Autofac/Core/Lifetime/LifetimeScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -363,10 +363,10 @@ public object CreateSharedInstance(Guid primaryId, Guid? qualifyingId, Func<obje
}

/// <inheritdoc />
public bool TryGetSharedInstance(Guid id, out object value) => _sharedInstances.TryGetValue(id, out value);
public bool TryGetSharedInstance(Guid id, [NotNullWhen(true)] out object? value) => _sharedInstances.TryGetValue(id, out value);

/// <inheritdoc/>
public bool TryGetSharedInstance(Guid primaryId, Guid? qualifyingId, out object value)
public bool TryGetSharedInstance(Guid primaryId, Guid? qualifyingId, [NotNullWhen(true)] out object? value)
{
return qualifyingId == null
? TryGetSharedInstance(primaryId, out value)
Expand Down
4 changes: 2 additions & 2 deletions src/Autofac/Core/Registration/ComponentRegistryBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ internal ComponentRegistryBuilder(IRegisteredServicesTracker registeredServicesT
_registeredServicesTracker.RegistrationSourceAdded += OnRegistrationSourceAdded;
}

private void OnRegistered(object sender, IComponentRegistration e)
private void OnRegistered(object? sender, IComponentRegistration e)
{
var handler = GetRegistered();

handler?.Invoke(this, new ComponentRegisteredEventArgs(this, e));
}

private void OnRegistrationSourceAdded(object sender, IRegistrationSource e)
private void OnRegistrationSourceAdded(object? sender, IRegistrationSource e)
{
var handler = GetRegistrationSourceAdded();

Expand Down
3 changes: 2 additions & 1 deletion src/Autofac/Core/Registration/ServiceRegistrationInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,8 @@ public void SkipSource(IRegistrationSource source)
{
EnforceDuringInitialization();

_sourcesToQuery = new Queue<IRegistrationSource>(_sourcesToQuery.Where(rs => rs != source));
// _sourcesToQuery always non-null during Initialization.
_sourcesToQuery = new Queue<IRegistrationSource>(_sourcesToQuery!.Where(rs => rs != source));
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
Expand Down
2 changes: 1 addition & 1 deletion src/Autofac/Core/Service.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public override string ToString()
/// </returns>
/// <exception cref="System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Justification = "This is an attempt to make Equals 'abstract' when it normally isn't.")]
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
throw new NotImplementedException(ServiceResources.MustOverrideEquals);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Autofac/Core/TypedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public TypedService(Type serviceType)
/// Gets a human-readable description of the service.
/// </summary>
/// <value>The description.</value>
public override string Description => ServiceType.FullName;
public override string Description => ServiceType.FullName!;

/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
Expand All @@ -56,7 +56,7 @@ public bool Equals(TypedService? other)
/// true if the specified <see cref="object"/> is equal to the current <see cref="object"/>; otherwise, false.
/// </returns>
/// <exception cref="NullReferenceException">The <paramref name="obj"/> parameter is null.</exception>
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
return Equals(obj as TypedService);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Autofac/Core/UniqueService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public UniqueService(Guid id)
/// true if the specified <see cref="object"/> is equal to the current <see cref="object"/>; otherwise, false.
/// </returns>
/// <exception cref="System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception>
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
var that = obj as UniqueService;

Expand Down
12 changes: 6 additions & 6 deletions src/Autofac/Diagnostics/DiagnosticTracerBase.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Autofac Project. All rights reserved.
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
Expand Down Expand Up @@ -52,7 +52,7 @@ namespace Autofac.Diagnostics
/// </para>
/// </remarks>
/// <seealso cref="DefaultDiagnosticTracer"/>
public abstract class DiagnosticTracerBase : IObserver<KeyValuePair<string, object>>
public abstract class DiagnosticTracerBase : IObserver<KeyValuePair<string, object?>>
{
/// <summary>
/// The list of event names to which this observer is subscribed.
Expand Down Expand Up @@ -207,7 +207,7 @@ public bool IsEnabled(string diagnosticName)
/// <summary>
/// Notifies the observer that the provider has finished sending push-based notifications.
/// </summary>
void IObserver<KeyValuePair<string, object>>.OnCompleted()
void IObserver<KeyValuePair<string, object?>>.OnCompleted()
{
// If there was something to dispose or clean up, here's where it would
// happen, but we don't have anything like that.
Expand All @@ -219,7 +219,7 @@ void IObserver<KeyValuePair<string, object>>.OnCompleted()
/// <param name="error">
/// An object that provides additional information about the error.
/// </param>
void IObserver<KeyValuePair<string, object>>.OnError(Exception error)
void IObserver<KeyValuePair<string, object?>>.OnError(Exception error)
{
// The internal diagnostic source isn't really going to experience an
// error condition (which is not the same as _reporting errors_) so
Expand All @@ -232,7 +232,7 @@ void IObserver<KeyValuePair<string, object>>.OnError(Exception error)
/// <param name="value">
/// The current notification information.
/// </param>
void IObserver<KeyValuePair<string, object>>.OnNext(KeyValuePair<string, object> value)
void IObserver<KeyValuePair<string, object?>>.OnNext(KeyValuePair<string, object?> value)
{
// This is what gets called when a new diagnostic event occurs.
Write(value.Key, value.Value);
Expand Down Expand Up @@ -400,7 +400,7 @@ protected virtual void OnRequestSuccess(RequestDiagnosticData data)
/// options.
/// </para>
/// </remarks>
protected virtual void Write(string diagnosticName, object data)
protected virtual void Write(string diagnosticName, object? data)
{
if (data == null || !IsEnabled(diagnosticName))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public MetadataFilterAttribute(string key, object value)
/// <exception cref="System.ArgumentNullException">
/// Thrown if <paramref name="parameter" /> or <paramref name="context" /> is <see langword="null" />.
/// </exception>
public override object ResolveParameter(ParameterInfo parameter, IComponentContext context)
public override object? ResolveParameter(ParameterInfo parameter, IComponentContext context)
{
if (parameter == null)
{
Expand Down Expand Up @@ -176,15 +176,16 @@ public override bool CanResolveParameter(ParameterInfo parameter, IComponentCont
// this is the place to do it.
var elementType = GetElementType(parameter.ParameterType);

return (bool)CanResolveMethod.MakeGenericMethod(elementType).Invoke(null, new[] { context, Key, Value });
// CanResolveMethod always returns a value.
return (bool)CanResolveMethod.MakeGenericMethod(elementType).Invoke(null, new[] { context, Key, Value })!;
}

private static Type GetElementType(Type type)
{
return type.IsGenericEnumerableInterfaceType() ? type.GenericTypeArguments[0] : type;
}

private static T FilterOne<T>(IComponentContext context, string metadataKey, object metadataValue)
private static T? FilterOne<T>(IComponentContext context, string metadataKey, object metadataValue)
{
// Using Lazy<T> to ensure components that aren't actually used won't get activated.
return context.Resolve<IEnumerable<Meta<Lazy<T>>>>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Fun
}
else if (serviceType.IsArray)
{
elementType = serviceType.GetElementType();
// GetElementType always non-null if IsArray is true.
elementType = serviceType.GetElementType()!;
limitType = serviceType;
factory = GenerateArrayFactory(elementType);
}
Expand Down Expand Up @@ -160,7 +161,9 @@ private static Func<int, IList> GenerateListFactory(Type elementType)
var parameter = Expression.Parameter(typeof(int));
var genericType = typeof(List<>).MakeGenericType(elementType);
var constructor = genericType.GetMatchingConstructor(new[] { typeof(int) });
var newList = Expression.New(constructor, parameter);

// We know that List<> has the constructor we need.
var newList = Expression.New(constructor!, parameter);
return Expression.Lambda<Func<int, IList>>(newList, parameter).Compile();
}

Expand Down
4 changes: 2 additions & 2 deletions src/Autofac/Features/Decorators/DecoratorService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public Service ChangeType(Type newType)
}

/// <inheritdoc />
public bool Equals(DecoratorService other)
public bool Equals(DecoratorService? other)
{
if (other is null)
{
Expand All @@ -64,7 +64,7 @@ public bool Equals(DecoratorService other)
}

/// <inheritdoc />
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
if (obj is null)
{
Expand Down
Loading

0 comments on commit 6595625

Please sign in to comment.