c# - 在 C# 中使用具有依赖注入(inject)的泛型类

标签 c# generics dependency-injection asp.net-core

我需要为我的服务创建一个通用方法,并根据我作为参数传递的对象类型使用存储库或其他方法。

例如,我有这些接口(interface):

public interface IServiceText
{
   Task<string> UpdateTextPosition(TextDto object);
   Task<string> UpdateTextSize(TextDto object);
   Task<string> UpdateOtherThingOnText(TextDto object);

}

public interface IServiceImage
{
   Task<string> UpdateImagePosition(ImageDto object);
   Task<string> UpdateImageSize(ImageDto object);
   Task<string> UpdateOtherThingOnImage(ImageDto object);

}

在订单中,我有实现接口(interface)的类(只是添加了重要的代码)和构造函数:

//Class ServiceImage
private readonly IRepository<Image> _repo;

public ServiceImage(IRepository<Image> repo) //Dependecy Injection of the IRepository Generic
{
    _repo = repo;
}

//Class ServiceText
private readonly IRepository<Text> _repo;

public ServiceText(IRepository<Text> repo) //Dependecy Injection of the IRepository Generic
{
    _repo = repo;
}

UpdateTextPosition 和 UpdateImagePosition 做完全相同的事情,但在不同的集合中(或使用不同的 IRepository 实例,我使用的是 MongoDB):

public async Task<string> UpdateTextPosition(TextDto object)
{
     var text = await _repo.FindAsync(object.Id);
     text.PosLeft = object.PosLef;
     text.PosRight = object.PosRight;
     await _repo.Update(text); 
     return text.Id; 

}

public async Task<string> UpdateImagePosition(ImageDto object)
{
     var image = await _repo.FindAsync(object.Id);
     image.PosLeft = object.PosLef;
     image.PosRight = object.PosRight;
     await _repo.Update(image);  
     return image.Id

}

编辑:(添加 ImageDto 和 TextDto)

public class ImageDto
{
     public ObjectId Id {get; set;}
     public int PosLeft {get; set;}
     public int PosTop {get; set;}
     public ICollection<string> PropertyImage1 {get; set;}
     public string PropertyImage2 {get; set;}
}


public class TextDto
{
     public ObjectId Id {get; set;}
     public int PosLeft {get; set;}
     public int PosTop {get; set;}
     public double PropertyText1 {get; set;}
     public string PropertyText2 {get; set;}
}

public class Image : Entity
    {
         public ObjectId Id {get; set;}
         public int PosLeft {get; set;}
         public int PosTop {get; set;}
         public ICollection<string> PropertyImage1 {get; set;}
         public string PropertyImage2 {get; set;}
         public string OtherPropertyImage {get; set;}
    }


public class Text : Entity
{
     public ObjectId Id {get; set;}
     public int PosLeft {get; set;}
     public int PosTop {get; set;}
     public double PropertyText1 {get; set;}
     public string PropertyText2 {get; set;}
     public string OtherPropertyText {get; set;}
}

和 IEntity:

/// <summary>
/// Generic Entity interface.
/// </summary>
/// <typeparam name="TKey">The type used for the entity's Id.</typeparam>
public interface IEntity<TKey>
{
    /// <summary>
    /// Gets or sets the Id of the Entity.
    /// </summary>
    /// <value>Id of the Entity.</value>
    [BsonId]
    TKey Id { get; set; }
}

/// <summary>
/// "Default" Entity interface.
/// </summary>
/// <remarks>Entities are assumed to use strings for Id's.</remarks>
public interface IEntity : IEntity<string>
{
}

和实体类:

/// <summary>
    /// Abstract Entity for all the BusinessEntities.
    /// </summary>
    //[DataContract]
    [Serializable]
    [BsonIgnoreExtraElements(Inherited = true)]
    public abstract class Entity : IEntity<string>
    {
        /// <summary>
        /// Gets or sets the id for this object (the primary record for an entity).
        /// </summary>
        /// <value>The id for this object (the primary record for an entity).</value>
        [DataMember]
        [BsonRepresentation(BsonType.ObjectId)]
        public virtual string Id { get; set; }
    }

我需要将“通用方法”移动到带有接口(interface) (ICommonService) 的新 CommonService 中,并获取对象类型并确定 IMongoRepository 使用的内容...我认为 Generic 是我的方式......但我已经阅读过它,但我不太理解这些示例,我希望在我的实际解决方案中以最佳方式实现它。

非常感谢!!

最佳答案

如果我正确理解了你的问题,那么你应该做如下事情:

首先为您的 DTO 创建一个通用接口(interface):

public interface IDtoCommon
{
    ObjectId Id { get; set; }
    int PosLeft { get; set; }
    int PosTop { get; set; }
}

以及您的实体的通用接口(interface):

public interface IEntityCommon
{
    ObjectId Id { get; set; }
    int PosLeft { get; set; }
    int PosTop { get; set; }
}

下面是您的 DTO 和实体的样子:

public class ImageDto : IDtoCommon
{
     public ObjectId Id {get; set;}
     public int PosLeft {get; set;}
     public int PosTop {get; set;}
     public ICollection<string> PropertyImage1 {get; set;}
     public string PropertyImage2 {get; set;}
}


public class TextDto : IDtoCommon
{
     public ObjectId Id {get; set;}
     public int PosLeft {get; set;}
     public int PosTop {get; set;}
     public double PropertyText1 {get; set;}
     public string PropertyText2 {get; set;}
}

public class Image : Entity, IEntityCommon
{
    public ObjectId Id { get; set; }
    public int PosLeft { get; set; }
    public int PosTop { get; set; }
    public ICollection<string> PropertyImage1 { get; set; }
    public string PropertyImage2 { get; set; }
    public string OtherPropertyImage { get; set; }
}

public class Text : Entity, IEntityCommon
{
    public ObjectId Id { get; set; }
    public int PosLeft { get; set; }
    public int PosTop { get; set; }
    public double PropertyText1 { get; set; }
    public string PropertyText2 { get; set; }
    public string OtherPropertyText { get; set; }
}

这是您的公共(public)服务的样子:

public interface ICommonService<TDto> where TDto : IDtoCommon
{
    Task<string> UpdatePosition(TDto @object);
}

public class CommonService<TDto, TEntity> : ICommonService<TDto>
    where TDto : IDtoCommon
    where TEntity : IEntityCommon
{
    private readonly IRepository<TEntity> m_Repository;

    public CommonService(IRepository<TEntity> repository)
    {
        m_Repository = repository;
    }

    public async Task<string> UpdatePosition(TDto @object)
    {
        var entity = await m_Repository.FindAsync(@object.Id);
        entity.PosLeft = @object.PosLeft;
        entity.PosTop = @object.PosTop;
        await m_Repository.Update(entity);
        return entity.Id.Value; 
    }
}

这是一个如何使用它的例子:

CommonService<TextDto, Text> service = new CommonService<TextDto, Text>(new Repository<Text>());

service.UpdatePosition(text_dto);

您应该考虑您的代码中是否有足够的重复来证明执行所有这些操作是合理的。

关于c# - 在 C# 中使用具有依赖注入(inject)的泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34300037/

相关文章:

C# Linq 或 Lambda 从类中获取 Dictionary<string, List<string>>

c# - 如何在 visual studio 2015 中管理 EF 6 迁移?

java - 如何使用参数 java.lang.reflect.Type 在泛型类中分配类型

asp.net-mvc - 依赖注入(inject)到 MVC 操作方法中

c# - 优化托管到 native 调用

c# - 无法通过应用程序配置连接自定义跟踪监听器类 - ConfigurationErrorsException

java - 如何处理重复的类型参数?

generics - 符合协议(protocol)的Swift泛型不能用来引用协议(protocol)?

android - 将 @Component.Builder 与构造函数参数一起使用

c# - DI/IoC、NHibernate 并帮助它们协同工作