Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WithProperty by expression #1123

Merged
merged 3 commits into from May 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/Autofac/RegistrationExtensions.cs
Expand Up @@ -882,6 +882,35 @@ private static Type[] GetImplementedInterfaces(Type type)
return registration.WithProperty(new NamedPropertyParameter(propertyName, propertyValue));
}

/// <summary>
/// Configure an explicit value for a property.
/// </summary>
/// <typeparam name="TLimit">Registration limit type.</typeparam>
/// <typeparam name="TReflectionActivatorData">Activator data type.</typeparam>
/// <typeparam name="TStyle">Registration style.</typeparam>
/// <typeparam name="TProperty">Type of the property being assigned.</typeparam>
/// <param name="registration">Registration to set property on.</param>
/// <param name="propertyExpression">Expression of a property on the target type.</param>
/// <param name="propertyValue">Value to supply to the property.</param>
/// <returns>A registration builder allowing further configuration of the component.</returns>
public static IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle>
WithProperty<TLimit, TReflectionActivatorData, TStyle, TProperty>(
this IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> registration,
Expression<Func<TLimit, TProperty>> propertyExpression,
TProperty propertyValue)
where TReflectionActivatorData : ReflectionActivatorData
{
if (registration == null) throw new ArgumentNullException(nameof(registration));
if (propertyExpression == null) throw new ArgumentNullException(nameof(propertyExpression));
if (propertyValue == null) throw new ArgumentNullException(nameof(propertyValue));

var propertyInfo = (propertyExpression.Body as MemberExpression)?.Member as PropertyInfo;
if (propertyInfo == null)
throw new ArgumentOutOfRangeException(nameof(propertyExpression), RegistrationExtensionsResources.ExpressionDoesNotReferToProperty);

return registration.WithProperty(new NamedPropertyParameter(propertyInfo.Name, propertyValue));
}

/// <summary>
/// Configure an explicit value for a property.
/// </summary>
Expand Down
14 changes: 11 additions & 3 deletions src/Autofac/RegistrationExtensionsResources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

59 changes: 31 additions & 28 deletions src/Autofac/RegistrationExtensionsResources.resx
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema

Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple

There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -135,4 +135,7 @@
<data name="OnlyIfRequiresCallbackContainer" xml:space="preserve">
<value>You can only attach a registration predicate to a registration that has a callback container attached (e.g., one that was made with a standard ContainerBuilder extension method).</value>
</data>
</root>
<data name="ExpressionDoesNotReferToProperty" xml:space="preserve">
<value>Expression does not refer to a property</value>
</data>
</root>
32 changes: 31 additions & 1 deletion test/Autofac.Test/ResolutionExtensionsTests.cs
@@ -1,7 +1,9 @@
using Autofac.Core;
using System;
using Autofac.Core;
using Autofac.Core.Activators.ProvidedInstance;
using Autofac.Core.Registration;
using Autofac.Test.Scenarios.Parameterisation;
using Autofac.Test.Scenarios.WithProperty;
using Xunit;

namespace Autofac.Test
Expand Down Expand Up @@ -91,5 +93,33 @@ public void WhenPredicateAndValueParameterSupplied_PassedToComponent()
Assert.Equal(a, result.A);
Assert.Equal(b, result.B);
}

[Fact]
public void RegisterPropertyWithExpression()
{
const string a = "Hello";
const bool b = true;
var builder = new ContainerBuilder();

builder.RegisterType<WithProps>()
.WithProperty(x => x.A, a)
.WithProperty(x => x.B, b);

var container = builder.Build();
var result = container.Resolve<WithProps>();

Assert.Equal(a, result.A);
Assert.Equal(b, result.B);
}

[Fact]
public void RegisterPropertyWithExpressionFieldExceptions()
{
const string a = "Hello";
var builder = new ContainerBuilder();

Assert.Throws<ArgumentOutOfRangeException>(() =>
builder.RegisterType<WithProps>().WithProperty(x => x._field, a));
}
}
}
11 changes: 11 additions & 0 deletions test/Autofac.Test/Scenarios/WithProperty/WithProps.cs
@@ -0,0 +1,11 @@
namespace Autofac.Test.Scenarios.WithProperty
{
public class WithProps
{
public string A { get; set; }

public bool B { get; set; }

public string _field;
}
}