Resolving Generic Interface with Autofac

前端 未结 2 1219
难免孤独
难免孤独 2020-12-02 15:48

Given the following code, how do I resolve the right SomeInstance in autofac?

public class BaseClass {}

public class SubClass1 : BaseClass {}

public class          


        
2条回答
  •  眼角桃花
    2020-12-02 16:12

    Correction. You cannot call MakeGenericType from the Container. I solved the issue of instantiating Generics using the 'TYPE' as the parameter on the Resolve call. The builder is registered.

            builder.RegisterGeneric(typeof (FakeRepository<>)).As(typeof (IRepository<>)).OnActivating(e =>
            {
                var typeToLookup = e.Parameters.FirstOrDefault() as TypedParameter;
                if (typeToLookup != null)
                {
                    var respositoryType = typeof (FakeRepository<>);
                    Type[] typeArgs = {typeToLookup.Value.GetType()};
                    var genericType = respositoryType.MakeGenericType(typeArgs);
                    var genericRepository = Activator.CreateInstance(genericType);
                    e.ReplaceInstance(genericRepository);
                }
            });
    

    Then the resolution happens like this, passing a TypedParameter to the Resolve. In this case I have a list of items (IItem) that are resolved that I want to create a repository for all of the items of that type.

            var items = container.Resolve>>();
            foreach (var item in items)
            {
                var repository = container.Resolve(typeof (IRepository), new TypedParameter(item.GetType(), item));
                Assert.IsNotNull(repository);
            }
    

    Thanks for your post it helped and I Hope this update helps.

提交回复
热议问题