我有3层架构应用程序。我的数据访问如下:
ICategoryRepository.cs
public interface ICategoryRepository
{
void Add(Category category);
}
CategoryRepository.cs
internal class CategoryRepository : ICategoryRepository
{
void ICategoryRepository.Add(Category category)
{
// Dbcontext goes here
}
}
我有一个Autofac模型在autofac容器中注册上面的类是:
public class RepositoryModule : Module
{
protected override void Load(ContainerBuilder builder)
{
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
base.Load(builder);
}
}
我有一个服务层,如下所示: 的 ICategoryService.cs
public interface ICategoryService
{
void Add(Category category);
}
CategoryService.cs
internal class CategoryService : ICategoryService
{
private ICategoryRepository _categoryRepository;
public CategoryService(ICategoryRepository categoryRepository)
{
_categoryRespoitory = categoryRepository;
}
void ICategoryService.Add(Category category)
{
_categoryRepository.Add(category);
}
}
同样,我有一个模块在容器中注册上面的类,
public class ServiceModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
}
}
在我的网站上,Global.asax.cs:
public class Global : System.Web.HttpApplication, IContainerProviderAccessor
{
static IContainerProvider _containerProvider;
public IContainerProvider ContainerProvider
{
get { return _containerProvider; }
}
void Application_Start(object sender, EventArgs e)
{
var builder = new ContainerBuilder();
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
_containerProvider = new ContainerProvider(builder.Build());
}
}
我的问题是,如何从网络上调用服务和DataAccess模块。
我的网站上没有数据访问参考,但我在网站上引用了服务模块
答案 0 :(得分:2)
您可以使用RegisterAssemblyModules
方法
void Application_Start(object sender, EventArgs e)
{
var builder = new ContainerBuilder();
IEnumerable<Assembly> assemblies = AppDomain.CurrentDomain.GetAssemblies();
if (HostingEnvironment.InClientBuildManager)
{
assemblies = assemblies.Union(BuildManager.GetReferencedAssemblies()
.Cast<Assembly>())
.Distinct();
}
builder.RegisterAssemblyModules(assemblies);
_containerProvider = new ContainerProvider(builder.Build());
}
为了让此代码正常工作,bin文件夹中的所有程序集都应该可用。
我使用BuildManager.GetReferencedAssemblies()
来避免在ASP.net回收过程之后出现问题。有关更多说明,请参阅autofac文档中的IIS Hosted Web Application。