NInject с универсальным интерфейсом - PullRequest
42 голосов
/ 07 февраля 2010

Я определил один интерфейс и один класс:

public interface IRepository<T>
{
}

public class RoleRepository:IRepository<Domain_RoleInfo>
{
}

Введите здесь:

public RoleService
{
    [Inject]
    public RoleService(IRepository<Domain_RoleInfo> rep)
    {
        _roleRep=rep;
    }
}

Как я могу выполнить инъекцию зависимостей с помощью Ninject, скажем, как связывать?

Я написал вспомогательный класс, как показано ниже, он отлично работает с неуниверсальным интерфейсом. Но как реорганизовать поддержку универсального интерфейса, как указано выше?

public class RegisterNinjectModule : NinjectModule
{
    public override void Load()
    {
        BindServices();
        BindRepositories();
    }

    private void BindServices()
    {

        FindAndBindInterfaces("RealMVC.Service.Interfaces", "RealMVC.Services");            
    }

    private void BindRepositories()
    {
        FindAndBindInterfaces("RealMVC.Repository.Interfaces", "RealMVC.Repositories");   
    }

    private void FindAndBindInterfaces(string interfaceAssemblyName, string implAssemblyName)
    {
        //Get all interfaces
        List<Type> interfaces = Assembly.Load(interfaceAssemblyName).GetTypes().AsQueryable().Where(x => x.IsInterface).ToList();
        IQueryable<Type> ts = Assembly.Load(implAssemblyName).GetTypes().AsQueryable().Where(x => x.IsClass);

        foreach (Type intf in interfaces)
        {
            Type t = ts.Where(x => x.GetInterface(intf.Name) != null).FirstOrDefault();
            if (t != null)
            {
                Bind(intf).To(t).InSingletonScope();
            }
        }
    }


}

Ответы [ 4 ]

81 голосов
/ 11 марта 2010

Это должно работать: -

Bind(typeof(IRepository<>)).To(typeof(Repository<>));

где: -

IRepository <> - это интерфейс вида: -

public interface IRepository<T> where T : class
{
 //...
}

Репозиторий <> - это класс вида: -

public class Repository<T> : IRepository<T> where T : class
{
  //...
}

Надеюсь, это поможет: -)

5 голосов
/ 07 февраля 2010

Это должно помочь выполнить то, что вы просите.

Сначала давайте определим два класса (InterfaceTypeDefinition и BindingDefinition).

InterfaceTypeDefinition содержит информацию о конкретном типе и его интерфейсах. Метод IsOpenGeneric определен в классе TypeExtensions.

public class InterfaceTypeDefinition
{
    public InterfaceTypeDefinition(Type type)
    {
        Implementation = type;
        Interfaces = type.GetInterfaces();
    }

    /// <summary>
    /// The concrete implementation.
    /// </summary>
    public Type Implementation { get; private set; }

    /// <summary>
    /// The interfaces implemented by the implementation.
    /// </summary>
    public IEnumerable<Type> Interfaces { get; private set; }

    /// <summary>
    /// Returns a value indicating whether the implementation
    /// implements the specified open generic type.
    /// </summary>
    public bool ImplementsOpenGenericTypeOf(Type openGenericType)
    {
        return Interfaces.Any(i => i.IsOpenGeneric(openGenericType));
    }

    /// <summary>
    /// Returns the service type for the concrete implementation.
    /// </summary>
    public Type GetService(Type openGenericType)
    {
        return Interfaces.First(i => i.IsOpenGeneric(openGenericType))
            .GetGenericArguments()
            .Select(arguments => openGenericType.MakeGenericType(arguments))
            .First();
    }
}

BindingDefinition содержит информацию о связи между службой и конкретной реализацией.

public class BindingDefinition
{
    public BindingDefinition(
        InterfaceTypeDefinition definition, Type openGenericType)
    {
        Implementation = definition.Implementation;
        Service = definition.GetService(openGenericType);
    }

    public Type Implementation { get; private set; }

    public Type Service { get; private set; }
}

Во-вторых, давайте реализуем метод расширения, который извлекает необходимую информацию.

public static class TypeExtensions
{
    public static IEnumerable<BindingDefinition> GetBindingDefinitionOf(
      this IEnumerable<Type> types, Type openGenericType)
    {
        return types.Select(type => new InterfaceTypeDefinition(type))
            .Where(d => d.ImplementsOpenGenericTypeOf(openGenericType))
            .Select(d => new BindingDefinition(d, openGenericType));
    }

    public static bool IsOpenGeneric(this Type type, Type openGenericType)
    {
        return type.IsGenericType 
            && type.GetGenericTypeDefinition().IsAssignableFrom(openGenericType);
    }
}

Теперь эти классы можно использовать для инициализации привязок в модуле.

public class RepositoryModule : NinjectModule
{
    public override void Load()
    {
        var definitions = Assembly.GetExecutingAssembly().GetTypes()
            .GetBindingDefinitionOf(typeof(IRepository<>));

        foreach (var definition in definitions)
        {
            Bind(definition.Service).To(definition.Implementation);
        }
    }
}
2 голосов
/ 03 марта 2011

Если вы импортируете расширение Ninject соглашений, его GenericBindingGenerator сможет вам помочь. Добавлена ​​поддержка универсальных интерфейсов.

0 голосов
/ 29 мая 2010

Просто вопрос о вашем FindAndBindInterfaces методе: внутри foreach у вас нет проблемы "замыкания" в переменной intf ? Я все еще не уверен, что понял, как работает проблема закрытия.

В любом случае, просто чтобы быть в безопасности, я думаю, что вы должны изменить свой foreach на что-то вроде:

foreach (Type intf in interfaces)
    {
        var tmp = intf;
        Type t = ts.Where(x => x.GetInterface(tmp.Name) != null).FirstOrDefault();
        if (t != null)
        {
            Bind(intf).To(t).InSingletonScope();
        }
    }
...