我觉得我对使用AutoFac可以做些什么感到困惑,有人可以让我走上正轨.
我有一个基本类型
class PersonBase{
public string SaySomething(){
return "I am base";
}
}
Run Code Online (Sandbox Code Playgroud)
我推导出两个具体的课程
class FakePerson : PersonBase{
public override string SaySomething(){
return "I'm so Fake";
}
}
class RealPerson : PersonBase{
public override string SaySomething(){
return "I am For Real";
}
}
Run Code Online (Sandbox Code Playgroud)
创建一个泛型类PersonHandler,以处理不同类型的人,并希望PersonHandler在适当的时候实例化该人,所以我不想要一个Person实例注入,只需要派生类型
class PersonHandler<T>
where T : PersonBase, new() {
T _Person;
public DoWork(){
_Person = new T();
_Person.SaySomething();
}
}
Run Code Online (Sandbox Code Playgroud)
现在我尝试使用处理程序,在注册下面详细说明的类型后,会有不同的结果.
var ph = contrainer.Resolve<PersonHandler<PersonBase>>();
ph.DoWork();
Run Code Online (Sandbox Code Playgroud)
我试图按如下方式注册类型
1. vBuilder.RegisterType<PersonHandler<FakePerson>>().As<PersonHandler<PersonBase>>();
Run Code Online (Sandbox Code Playgroud)
这给了我一个错误,说明PersonHandler<FakePerson>
不能分配PersonHandler<PersonBase>
(或者反过来我不会重新分配哪个)
2. vBuilder.RegisterGeneric<typeof(PersonHandler<>)>
vBuilder.RegisterType<FakePerson>().As<PersonBase>(); …
Run Code Online (Sandbox Code Playgroud) 我对Autofac很新,我每次初始化时都试图在类上设置公共属性.这是场景.我有许多类继承自"实体",遵循这种基本格式......
public class Person : Entity
{
public virtual DataContext ServiceContext { get; set; }
public string FirstName {get; set;}
...
}
Run Code Online (Sandbox Code Playgroud)
这些类通常由LINQ查询实例化,如下所示:
var context = SomeContext(connection);
var people = context.Query<Person>().Where(item => item.FirstName == "Joe").ToList();
Run Code Online (Sandbox Code Playgroud)
我想要实现的是每次实例化时将"context"对象传递到Person类的ServiceContext属性.在此示例中,people列表中的每个Person都将设置此属性.
理想情况下,我会通过"实体"的构造函数传递DataContext,但问题是我无法访问Entity或Linq提供程序,因为它们来自第三方.所以我的问题是,使用Autofac,如何将"上下文"注入到"实体"派生的每个类的"ServiceContext"属性中?似乎OnActivating事件接近我的需要,但我无法让它工作.
我正在使用Autofac在我的解决方案中实现IoC,但我怀疑我是否做得对.这是场景:
我有一些Manager
类都来自BaseManager
类.该BaseManager
有一个protected User CurrentUser
领域.我正在尝试做的是解决CurrentUser
使用Autofac.我编写了一个IUserProvider
接口并实现了几个类(例如WebUserProvider
和WinformsUserProvider
).
然后我在下面注册了我的提供者(例如,在Global.asax)
:
builder.Register(c => new WebUserProvider(...)).As<IUserProvider>();
Run Code Online (Sandbox Code Playgroud)
container
在我的类中访问)?我可以使用单例或服务定位器模式,但看起来它是反模式.那么我应该如何解决我的依赖?dependency-injection ioc-container inversion-of-control autofac
我正在尝试在我的项目中使用autofac.所以在Mef中,我可以使用此代码获取接口的实例:
private static CompositionContainer _container;
public static void Initialize()
{
string path = AppDomain.CurrentDomain.BaseDirectory.Contains(@"\bin") ?
AppDomain.CurrentDomain.BaseDirectory :
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
//DirectoryCatalog catalog = new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"), "*.Data*.dll");
DirectoryCatalog catalog = new DirectoryCatalog(path, "*.dll");
_container = new CompositionContainer(catalog);
_container.ComposeParts();
}
private static void CheckContainer()
{
if (_container == null)
{
Initialize();
}
}
public static T GetInstance<T>()
{
CheckContainer();
return _container.GetExportedValue<T>();
}
Run Code Online (Sandbox Code Playgroud)
但autofac似乎让我感到困惑......我如何使用autofac将此功能添加到我的应用程序?
谢谢
我将该代码更改为:
private static ContainerBuilder _container;
private static IContainer container;
public static void Initialize()
{
_container = new ContainerBuilder(); …
Run Code Online (Sandbox Code Playgroud) 我无法使用MembershipReboot
新的ASP MVC5模板和Autofac
.我使用默认的MVC5模板来设置站点,然后尝试连接MembershipReboot
框架作为模板附带的ASP Identity框架的替代.
我有这个问题试图解决一个IOwinContext
从Autofac
容器.这是我在Startup课程中的布线(切入基础知识).这是MembershipReboot Owin
应用样品中使用的接线(除非他使用Nancy).
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.Register(c => new DefaultUserAccountRepository())
.As<IUserAccountRepository>()
.As<IUserAccountQuery>()
.InstancePerLifetimeScope();
builder.RegisterType<UserAccountService>()
.AsSelf()
.InstancePerLifetimeScope();
builder.Register(ctx =>
{
**var owin = ctx.Resolve<IOwinContext>();** //fails here
return new OwinAuthenticationService(
MembershipRebootOwinConstants.AuthenticationType,
ctx.Resolve<UserAccountService>(),
owin.Environment);
})
.As<AuthenticationService>()
.InstancePerLifetimeScope();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
ConfigureAuth(app);
app.Use(async (ctx, next) =>
{
using (var scope = container.BeginLifetimeScope(b =>
{ …
Run Code Online (Sandbox Code Playgroud) 我有这样的界面:
public interface ICategoryFacade
{
IEnumerable<Category> Get();
Category Get(int id);
int Post(Category model);
int Put(Category model);
int Patch(Category model);
int Delete(int id);
}
Run Code Online (Sandbox Code Playgroud)
我上课了:
public class CategoryFacade : ICategoryFacade
{
MyContext _dbContext = new MyContext ();
public IEnumerable<Category> Get()
{
return _dbContext.Categories;
}
public Category Get(int id)
{
return _dbContext.Categories.FirstOrDefault(m => m.CategoryID == id);
}
public int Post(Category model)
{
return 0;
}
public int Put(Category model)
{
return 0;
}
public int Patch(Category model)
{
return 0;
}
public …
Run Code Online (Sandbox Code Playgroud) 我有一个MVC/WebApi应用程序.我开始使用Autofac来解决这个问题.
Autofac工作.但是,随机我会收到错误:
尝试创建"SomeController"类型的控制器时发生错误.确保控制器具有无参数的公共构造函数.
当我清理解决方案并重建时.没有更多的错误.我以为这是我的Visual Studio实例(可能需要运行修复).但是,我只是尝试发布到IIS,我再次收到错误.
有没有人遇到过这个问题,能有人帮帮我吗?
这是一些代码细节:
我所有的注册都是在这样的模块中完成的:
public class CryptographyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AesCryptographyService>()
.As<IAesCryptographyService>()
.InstancePerRequest();
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用它来引导Autofac:
public static class Bootstrapper
{
public static void Run()
{
BootStrapAutofac();
}
private static void BootStrapAutofac()
{
var builder = new ContainerBuilder();
var localAssemblies = GetLocalAssemblies();
builder.RegisterApiControllers(localAssemblies);
builder.RegisterControllers(localAssemblies);
builder.RegisterAssemblyModules(localAssemblies);
//build container
var container = builder.Build();
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
var mvcResolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(mvcResolver);
}
private static Assembly[] GetLocalAssemblies() …
Run Code Online (Sandbox Code Playgroud) 我有一个webforms项目,但我正在使用WebAPI进行Web服务.我正在尝试实现Autofac.我正进入(状态:
'MyController' does not have a default constructor
Run Code Online (Sandbox Code Playgroud)
根据Autofac文档,我的配置正确,但显然存在问题.我使用的是Visual Studio 2010/.Net 4.这是我的Application_Start
private void Application_Start(object sender, EventArgs e)
{
//This enables api controllers in a separate class library
GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new AssembliesResolver());
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
//Elmah for webapi
GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
var builder = new ContainerBuilder();
//Register DbContext
builder.RegisterType<MyDbContext>()
.As<IMyDbContext>()
.InstancePerRequest();
//Register service layer
var businessLayer = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
var container = builder.Build();
_containerProvider = new ContainerProvider(container);
var …
Run Code Online (Sandbox Code Playgroud) 我有一个DelegatingHandler
我需要注册的类库中的自定义Autofac
.webapi主机解析它对运行时的依赖性,因此主机没有对此库的引用.
public class LocalizationHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken )
{}
}
Run Code Online (Sandbox Code Playgroud)
在我的Autofac初始化程序类中,我尝试过以下方法:
protected override void Load( ContainerBuilder builder )
{
builder.RegisterType<LocalizationHandler>();
builder.Register(c => new LocalizationHandler());
}
Run Code Online (Sandbox Code Playgroud)
在主机中注册此类处理程序的常规方法是:
public static void Register(HttpConfiguration httpConfiguration)
{
httpConfiguration.MapHttpAttributeRoutes();
httpConfiguration.MessageHandlers.Add(new LocalizationHandler());
}
Run Code Online (Sandbox Code Playgroud)
但是我没有访问这里的主机项目.任何想法如何注入处理程序ContainerBuilder
?
我在尝试使用Sitecore 8.2的Autofac DI时收到以下错误:
依赖项解析程序的类型为"Sitecore.Mvc.Controllers.SitecoreDependencyResolver",但预计类型为"Autofac.Integration.Mvc.AutofacDependencyResolver".它似乎也没有使用Castle Project中的DynamicProxy进行包装.此问题可能是DynamicProxy实现更改或使用其他代理库来包装依赖项解析程序的结果.
任何想法:
autofac ×10
c# ×4
asp.net-mvc ×3
asp.net ×1
generics ×1
odata ×1
owin ×1
sitecore ×1
sitecore8 ×1
sitecore8.2 ×1