Unity config xml injection constructor pass parameter of type Func<Guid>

Jun 19, 2014 at 10:42 AM
I need to pass a value from the membership provider namely

(Guid)Membership.GetUser().ProviderUserKey;

I can do this in code using

Func<Guid> sessionIdProvider = () => (Guid) Membership.GetUser().ProviderUserKey;

and the using the container registertype. However I want to be able to do this in the XML config file rather than code. Can this be done easily or do I need a custom resolver to sort this out.

Any suggestions?
Jun 19, 2014 at 1:35 PM
I would create an interface IUserProvider that has a method Guid GetUserKey() and them create a class that implement this interface and use the membership to return the key.
Jun 19, 2014 at 2:15 PM
ended up with this code which seems to do what I want
public sealed class UserKeyProviderParameterValueElement : ValueElement, IDependencyResolverPolicy
    {
        #region Private methods

        private Func<Guid> CreateInstance()
        {
            Func<Guid> value = () => (Guid)Membership.GetUser().ProviderUserKey;            

            return value;
        }

        #endregion

        #region Public override methods

        public override InjectionParameterValue GetInjectionParameterValue(IUnityContainer container, Type parameterType)
        {           
            return (new InjectionParameter(parameterType, CreateInstance()));
        }

        #endregion

        #region IDependencyResolverPolicy Members

        public Object Resolve(IBuilderContext context)
        {           
            return (CreateInstance());
        }

        #endregion

        #region Public properties

        [ConfigurationProperty("userKeyProvider", IsRequired = true)]
        public String UserKeyProvider
        {
            get { return ((String)base["userKeyProvider"]); }

            set { base["userKeyProvider"] = value; }
        }

        #endregion
    }
public sealed class UserKeyProviderParameterInjectionElementExtension : SectionExtension
    {
        public override void AddExtensions(SectionExtensionContext context)
        {
            context.AddElement<UserKeyProviderParameterValueElement>("userKeyProvider");
        }
    }
Then in the config file

<sectionExtension type="MyAssembly.UserKeyProviderParameterInjectionElementExtension, MyAssembly" />

which allows me to use this on the injection constructor

<param name="userKeyProvider">
<userKeyProvider/>
</param>