Autofac注册通用存储库,其中T不是类

时间:2019-07-02 09:33:33

标签: c# generics autofac

当尝试解析通用存储库以进行数据库访问时遇到一个问题。当我使用这两个作为仓库实现/接口时,我无法解决例如function acf_load_post_type_choices( $field ) { $post_types = get_post_types(); if($post_types) { // reset choices $field['choices'] = array(); // get the textarea value from options page without any formatting if ( is_array( $post_types[0] ) ) { $getTypeSlugs = $post_types[0]; $getTypeNames = $post_types[0]; // Array( supported_format_1, supported_format_2 ... ) } else { } array_unshift($getTypeSlugs,'all','standard'); array_unshift($getTypeNames,'all','standard'); //create a string from formatSlug $values = implode("\n", $post_types ); //create a string from category Name $labels = implode("\n", $post_types); //Add an "all"-options //devide the strings into seperate objects $values = explode("\n", $values); $labels = explode("\n", $labels); $labels = array_map('ucfirst', $labels); // loop through array and add to field 'choices' foreach( array_combine($values, $labels ) as $value => $label ) { $field['choices'][ $value ] = $label; } // return the field return $field; } } add_filter('acf/load_field/name=posts_by_type', 'acf_load_post_type_choices', 1);

接口:

IRepository<ICustomer>

实施:

public interface IRepository<T> where T : IDbModel
{ ... }

但是当我在两种情况下都用public class Repository<T> : IRepository<T> where T : DbModel { ... } 替换IDbModelDbModel时,都可以正常工作。

我的注册如下:

class

出于完整性考虑,以下是builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)); builder.RegisterType<DbModel>().As<IDbModel>(); builder.RegisterType<Customer>().As<ICustomer>();

ICustomer

public interface ICustomer : IDbModel { ... }

Customer

public class Customer : DbModel, ICustomer { ... }

IDbModel

还有public interface IDbModel { ... } (我在删除DbModel时检查了它是否起作用,但没有用):

abstract

我想知道是否可以通过某种方式进行第一次尝试?

1 个答案:

答案 0 :(得分:1)

通过要求 Autofac 解决IRepository<ICustomer>,它将尝试解决Repository<ICustomer>,而ICustomer不是DbModel

要解决该错误,您应该将IRepository<TModel>上的类类型约束替换为接口类型约束。

 public class Repository<T> : IRepository<T> 
    where T : IDbModel 
 { }